Huum - Info db2 Notes PR
Huum - Info db2 Notes PR
Huum - Info db2 Notes PR
DB2 is the RDBMS developed by IBM for storing and accessing heavy
data.
In the SYSTEM SPACE, default tables called DB2 catalog tables & DB2
directory
tables are stored.
DB2 Catalog tables store the information of the user created database
objects.
SYSIBM.SYSTABLESPACES store tablespaces’ information.
SYSIBM.SYSTABLES store tables’ information.
SYSIBM.SYSCOLUMNS store columns’ information.
SYSIBM.SYSVIEWS store views’ information.
DB2 Directory tables store the information about the physical memory
locations of
database objects.
INDEX
Table Table View1
1 2
Row Columns
s
Db2 Database
Table: Table is the entity where we can store the data in the form of rows
and columns.
Segmented table space: In this type of TS, a page can hold ONLY one
table’s data.
Partitioned table space: In this type of TS, a set of pages are grouped
into a partition and only specific data is stored in each partition.
DDL
CREATE
ALTER
DROP
DML
INSERT
UPDATE
DELETE
SELECT
DCL
GRANT
REVOKE
DDL: Data Definition
CREATE:
language:
It is used to create database objects.
Creating a database:
CREATE DATABASE DB123.
Creating a table space:
CREATE TABLE SPACE TS123
STORGROUP3
PAGESIZE 16K
SEGMENTED IN DB123.
Creating a table:
CREATE TABLE EMP_TBL
(EMP_ID INT NOT NULL,
EMP_NAME CHR(30),
EMP_DEPT SMALL INT,
EMP_SAL DECIMAL (11,2),
EMP_ADDR VARCHAR(50),
EMP_JOIN_DT DATE NOT NULL WITH DEFAULT,
EMP_JOIN_TM TIME,
TRANS_TS TIMESTAMP.
PRIMARY KEY (EMP_ID),
ON DELETE CASCADE)
IN DB123.TS123
CONSTRAINTS
Constraint is a mechanism to control the data in the tables.
1. Primary Key.
2. NULL Constraints
3. Referential Integrity
Constraints
Primary Key:
It is used to uniquely identify a row in the table.
When primary key constraint set on a column it does not allow duplicate
or null values.
Foreign Key: It is used to build the relationship between the tables. It must be a primary key of the
table and when we use this in the other table then it becomes as a foreign Key.
Table in which it is primary key then it is called Parent table and the table in which it is foreign key
then it is called child table.
RI rules :
1. Insert Rule
2. Update Rule
3. Delete Rules
- ON DELETE CASCADE
- ON DELETE RESTRICT
- ON DELETE SET NULL
Referential Integrity
INSERT RULE : It says before inserting a row with new foreign key value,
insert it first into parent table.
UPDATE RULE : It says before updating a row with new foreign key value,
update it first in the parent table.
DELETE Rules :
1. ON DELETE CASCADE : It says when a parent table row is deleted, the corresponding
rows in all child tables also get deleted.
2. ON DELTE RESTRICT : It says when a parent table row with corresponding rows in
child tables is to be deleted, then a restriction is applied. So, first, delete the child table
rows and then parent table row.
3. ON DELETE SET NULL : It says when a parent table row is deleted, the foreign key
values for the corresponding rows in all child tables are set to NULL.
DDL: Data Definition language:
ALTER:
Note: A column can be added only as the last column in the table. If we need to add the column in
between the columns then we need to drop and create new table.
We can change the data types and data lengths.
We can increase/decrease the data length if a table is empty. But if the table is non empty we can
only increase the data length.
DROP:
If all the values are specified, then column names need not be specified.
INSERT INTO EMP_TBL
(EMP_ID, EMP_NAME)
VALUES (0314,’ANUUSHA’)
UPDATE:
The above code will update all EMP-SAL column values in the table.
UPDATE EMP-TBL
SET EMP-SAL=EMP-SAL+1000
WHERE DEPT=’D1;
WHERE clause is used to specify a condition based on which rows selective.
DML: Data Manipulation Language
DELETE:
It is used to delete the rows from the table.
DCLGEN will avoid the conversion errors i.e., avoids any mismatch in data types and data lengths.
DB2 Program Preparation
DB2 Program preparation involves the following steps :
Runtime
Supervisor
Execution
Pre-compilation
Pre-compilation is the process of separating COBOL and DB2 statements to generate
a Modified
Source Code and DBRM.
1. The pre-compiler utility DSNHPC checks the syntax errors of DB2 statements
before placing them into DBRM (Database Request Module).
2. It replaces all the DB2 statements by COBOL CALL statements in the Modified
Source Code.
3. It places a TIMESTAMP token in both Modified Source Code and DBRM.
1. BIND utility IKJEFT01 checks the syntax errors of DB2 statements in DBRM. It not
only checks the errors but also checks whether the columns and tables specified
exist or not by comparing with DB2 catalog tables.
2. BIND checks the authorization of the user for BINDING and EXECUTING the queries.
3. BIND component, OPTIMIZER using the statistics of RUNSTAT utility generates the
available access paths. Among the available access paths, it chooses the best one
and place it into the PACKAGE.
1. BIND utility IKJEFT01 checks the syntax errors of DB2 statements in DBRM. It not
only checks the errors but also checks whether the columns and tables specified
exist or not by comparing with DB2 catalog tables.
2. BIND checks the authorization of the user for BINDING and EXECUTING the queries.
3. BIND component, OPTIMIZER using the statistics of RUNSTAT utility generates the
available access paths. Among the available access paths, it chooses the best one
and place it into the PACKAGE.
4. One or more PACKAGES are bound again into an EXECUTABLE PLAN.
COMPILATION
Compilation is the process of checking syntax errors and converts Source code into
object module.
Compiler IGYCRCTL takes Modified Source Code as input and generates Object Module.
LINK-EDIT
LINK-EDIT is the process of linking object modules into an single executable load
module.
Execution
Runtime Supervisor allows execution only when TIMESTAMP tokens match between Load
module
and PLAN.
If they do not match, it abends the program with SQLCODE -818.
MEMBER specifies the DBRM name which is the input for BIND process.
ACTION
ACTION(ADD) - It includes the new PACKAGE information in
SYSIBM.SYSPACKAGES
ACTION(REPLACE) - It overrides the existing PACKAGE information in
SYSIBM.SYSPACKAGES with the new one.
BIND Parameters
OWNER specifies the owner id of the tables used in the program.
It is usually the Project ID.
OWNER ID is same in both PRODUCTION and DEVELOPMENT regions.
OWNER(ALLST) QUALIFIER(ALLST1)
QUALIFIER(ALLST2)
QUALIFIER(ALLST3)
BIND Parameters
EXPLAIN is a DB2 tool used to generate the access paths’ information into EXPLAIN
Tables.
These tables will help the DBA to analyze the Query performance.
Access paths’ information – CPU consumption time, CPU resource utilization, CPU cost,
etc.
BIND Parameters
VALIDATE will check the authorization of the USER ID for BINDING and EXECUTING the
queries.
BIND Parameters
ACQUIRE will allocate the locks on tablespaces i.e., allocates the tabvlespaces.
ROLLBACK : It does not the save the changes permanently till the last commit point.
Locking modes :
1. SHARE Lock (S-lock) : It allows to just read the data in tablespaces.
More than once user can issue S-lock on same data.
What is a Cursor ?
Cursor is a pointer to a row in the resultant table.
1. Declaring cursor.
2. Opening the cursor.
3. Fetching the cursor.
4. Closing the cursor.
Declaring the cursor
EXEC SQL
DECLARE EMPCUR CURSOR
FOR
SELECT EMP_SAL FROM EMP_TBL
WHERE DEPT_ID = ‘D6’
END-EXEC.
DECLARE CURSOR statement just creates the cursor for the associated query but the
query is not executed.
CURSOR WITH HOLD : It is used to keep the cursor open even after COMMIT is issued
EXEC SQL
DECLARE EMPCUR CURSOR WITH HOLD
FOR
SELECT EMP_SAL FROM EMP_TBL
WHERE DEPT_ID = ‘D6’
END-EXEC.
To Update the table using cursor, use FOR UPDATE OF clause
EXEC SQL
DECLARE EMPCUR CURSOR WITH HOLD
FOR
SELECT EMP_SAL FROM EMP_TBL
WHERE DEPT_ID = ‘D6’
FOR UPDATE OF EMP_SAL
END-EXEC.
Opening the cursor
EXEC SQL
OPEN EMPCUR
END-EXEC.
When OPEN CURSOR statement is processed, then the query associated with the
cursor is executed, the resultant table is created and the cursor is positioned at the
FIRST ROW in the resultant table.
Fetching the cursor
EXEC SQL
FETCH EMPCUR
INTO :HV-EMP-SAL
END-EXEC.
When FETCH CURSOR statement is processed, then the row to which cursor is
currently pointing to is retrieved into the program.
Each time FETCH cursor statement executes, one row is retrieved and so SQLCODE = 0.
To retrieve all rows, FETCH till SQLCODE = 100.
Closing the cursor
EXEC SQL
CLOSE EMPCUR
END-EXEC.
When CLOSE CURSOR statement is processed, then both the CURSOR and the
RESULTANT TABLE are destroyed.
Write a program to increment salaries of employees of
ID DIVISION.
desired DEPT?
2000-FETCH-PARA.
PROGRAM-ID. PROG1. EXEC SQL
DATA DIVISION. FETCH EMPCLR
WORKING-STORAGE SECTION. INTO :HV-EMP_SAL
EXEC SQL END-EXEC
INCLUDE SQLCA 3000-PROCESS-PARA.
END-EXEC. EVALUATE SQLCODE
EXEC SQL WHEN 0
INCLUDE DCLEMP ADD WS-SAL-INC TO HV-EMP-SAL
END-EXEC. EXEC SQL
01 WS-UPD-CNT PIC 9(2) VALUE 0. UPDATE EMP_TBL
01 WS-SAL-INC PIC 9(5). SET EMP_SAL = :HV-EMP-SAL
PROCEDURE DIVISION.
0000-MAIN-PARA. WHERE CURRENT OF EMPCUR
PERFORM 1000-INITIALIZE-PARA. END-EXEC
PERFORM 2000-FETCH-PARA. ADD +1 TO WS-UPD-CNT
PERFORM 3000-PROCESS-PARA UNTIL SQLCODE IF WS-UPD-CNT=50
NOT = 0. EXEC SQL
PERFORM 9000-CLOSE-PARA. COMMIT
STOP RUN. END-EXEC.
1000-INTIALIZE-PARA. MOVE 0 TO WS-UPD-CNT
EXEC SQL END-IF
DECLARE EMPCUR CURSOR WITH HOLD WHEN OTHER
FOR DISPLAY 'SQLCODE:'SQLCODE.
SELECT EMP_SAL FROM EMP_TBL END-EVALUATE.
WHERE DEPT_ID = :HV_DEPT_ID PERFORM 2000-FETCH-PARA.
FOR UPDATE OF EMP_SAL 9000-CLOSE-PARA
END-EXEC. EXEC SQL
ACCEPT HV-DEPT-ID. CLOSE EMPCUR
ACCEPT WS-SAL-INC. END-EXEC.
EXEC SQL
OPEN EMPCUR
END-EXEC.
VIEWS
VIEW is a database object used to provide data security.
VIEW is just a virtual table which acts like a window to the base table data.
It provides data security by restricting user from accessing secure columns of base
table.
Creating a VIEW :
CREATE VIEW V_CC_TBL
AS
SELECT CC_NUM, CC_EXP_DT
FROM CC_TBL
When user is granted access to view V-CC-TBL, he can access only CC_NUM
and CC_EXP_DT of base table CC_TBL
Note : AVG will give an incorrect value when the column has null
values.
Example :
SELECT DEPT_ID, COUNT(*) FROM EMP_TBL
GROUP BY DEPT_ID
HAVING COUNT(*) > 3
Syntax : SELECT - - - - - - - - -
WHERE - - - (SELECT - - - - - - - - - - - - - -)
Outer Inner
Query / Query / Sub
Main Query Query
1. Non-correlated sub-queries.
2. Correlated sub-queries.
Correlated sub-queries : First the Outer Query executes and for each
row of outer
query, the inner query executes i.e., first the outer query executes then
the inner
query.
Non-correlated Sub-queries
First the Inner Query executes and then based on its result, the Outer
query
executes.
Types of Joins :
1. INNER JOIN
2. OUTER JOIN
- LEFT OUTER JOIN
- RIGHT OUTER JOIN
- FULL OUTER JOIN
INNER JOIN
INNER JOIN is used to retrieve matched rows from the joining tables.
EMP_TBL DEPT_TBL
E01 RAMU D4 10000 D1 IT
E02 RAMU D7 20000 D2 HR
E03 RAMU D2 30000 D3 ADMN
E04 RAMU D6 40000 D4 PAYROLL
E05 RAMU D2 20000 D5 MAINT
E06 RAMU D1 15000
This will retrieve all the rows from both the tables but only unique rows
are retrieved.
This will retrieve all the rows from both the tables including duplicate
rows.
Performance Tuning
DB2 Performance Tuning Techniques :
1. By using Indexes
2. By using DB2 utilities – RUNSTAT and REORG
3. By avoiding arithmetic operations in DB2 queries.
4. By using Joins
Index
Index is a database object used to improve the DB2 performance.
When an index is created on a column, it does not allow duplicate values
but allows
a single NULL value.
//JOB1 JOB - - - - - -
//STEP1 EXEC PGM=IKJEFT01
//SYSTSIN DD *
RUNSTAT DB123.TS123
/*
When RUNSTAT holds the latest information, OPTIMIZER can generate the
BEST
ACCESS PATH which will inturn improve the DB2 performance.
DB2 Utilities
REORG utility : When it is run, the tablespace memory is reorganized
i.e., all the
data pages are accumulated releasing the unused pages into the free
memory.
//JOB1 JOB - - - - - -
//STEP1 EXEC PGM=IKJEFT01
//SYSTSIN DD *
REORG DB123.TS123
/*
This query retrieves the entire data from both the tables and then applies the
WHERE condition.
This query retrieves only the filtered data satisfying the ON condition and then
applies the WHERE condition.