DB2 For z/OS
DB2 For z/OS
Storing and retrieving data cannot be done efficiently DBMS is efficient to use as there are a wide variety of
in a file system methods to store and retrieve data
No backup and recovery of data exists DBMS provides backup and recovery of data
Security is very low Security is high
Redundancy of data is greater Redundancy of data is low
Data inconsistency is higher Data inconsistency is lower
Access is slow Access is faster
Concurrency is very low Concurrency is very high
DB2 for z/OS
DB2 for z/OS is a relational database management system (RDBMS) that runs on the mainframe.
A relational database is a database in which all of the data is logically contained in tables. These databases are organized
according to the relational model.
In a relational database, data exists in one or more tables and each table contains a specific number of columns and a
number of unordered rows
DB2 enables users to create, update and control relational databases using Structured Query Language (SQL)
DB2 database supports object oriented features and non-relational structure with XML
There are two types of storage structures based on the type of storage
Table space
Index space
DB2 for z/OS
The figure to the right represents a simplified structure of
a DB2 database
Only the storage group, table space and index space have
the physical existence. Rest all components are logical
concepts.
Storage Group is a physical DASD with a collection of
same type of volumes. It can have data sets in which the
tables and indexes are actually stored. A table space or
Index space is associated with one or more of these
physical data sets.
Table and database have no actual physical
representation.
Table space contains one or more tables
DB2 for z/OS
Storage Group: A set of volumes on disks that hold the data sets in which tables and indexes are stored
Databases A set of DB2 structures that include a collection of tables, their associated indexes and the table spaces in
which they reside
Table space: A table space is a set of volumes on disks that hold the data sets in which tables are actually stored. A table
space can contain one or more tables.
Table: All data in a DB2 database is presented in tables, which are collection of rows all having the same columns. A table
that holds persistent user data is a base table. A table that holds data temporarily is a temporary table.
View: A view is an alternative way of representing data that exists in one or more tables. A view can include all or some of
the columns from one or more base tables.
Index space: An Index space stores the indexes for the table space. Index space can contain more than one index. Index
space is similar to table space but contains only indexes in it. When an index is created, an index space will be created
automatically.
Index: An index is an ordered set of pointers to the data in a DB2 table. The index is stored separately from the table.
Table
A Table in DB2 is a logical object that stores data in the form of columns and rows
The rows of the table do not have a specified order but the columns of the table have the order that is specified when the
table is created
A column in a table is associated with a specific data type and a column stores values of the same type
Before a table can be created, its database and table space must exist
To create a new table, CREATE TABLE statement is used
Assume that the NEWEMP table has the following two check constraints:
Employees cannot receive a commission that is greater than their salary
Department numbers must be between ‘001’ to ‘100’, inclusive
The below INSERT statement adds an employee who has a salary of $70000 and a commission of $7000.
It succeeds because it satisfies both constraints.
The below INSERT statement fails because $15000 commission is higher than the $10000 salary. The INSERT statement
violates the check constraint on NEWEMP.
The below UPDATE statement succeeds because it satisfies the constraints that are defined on the NEWEMP table.
UPDATE NEWEMP
SET DEPT = ’011’
WHERE FIRSTNME = ’JOHN’ AND LASTNAME= ’HAVARD’;
The below UPDATE statement fails because the value of DEPT is ‘158’ that violates the check constraint on NEWEMP
that DEPT values must be between ‘001’ and ‘100’
UPDATE NEWEMP
SET DEPT = ’158’
WHERE FIRSTNME = ’JOHN’ AND LASTNAME= ’HAVARD’;
The below UPDATE statement succeeds because it satisfies the constraints that are defined on the NEWEMP table.
UPDATE NEWEMP
SET DEPT = ’011’
WHERE FIRSTNME = ’JOHN’ AND LASTNAME= ’HAVARD’;
The below UPDATE statement fails because the value of DEPT is ‘158’ that violates the check constraint on NEWEMP
that DEPT values must be between ‘001’ and ‘100’
UPDATE NEWEMP
SET DEPT = ’158’
WHERE FIRSTNME = ’JOHN’ AND LASTNAME= ’HAVARD’;
MGRNO DEPTNO
====== ======
000010 A00
000020 B01
000030 C01
------ D01
000050 E01
Accessing DB2 Data
Selection of all columns
Use a * in the SELECT clause to retrieve all columns from
the table. DB2 selects the columns in the order that the
columns are declared in that table.
SELECT *
FROM DEPT
WHERE ADMRDEPT = ’A00’;
ADMRDEPT
========
A00
D11
E01
Accessing DB2 Data
Selection of derived columns and naming the resulting columns
You can select columns that are derived from a constant, an expression or a function. With the AS clause
you can name the resulting columns.
SELECT EMPNO, (SALARY + COMM) AS TOTAL_SAL
FROM EMP;
EMPNO TOTAL_SAL
====== =========
000290 16567.00
000310 17172.00
200310 17172.00
000260 18630.00
000300 19170.00
000210 19732.00
.
.
.
Accessing DB2 Data
Concatenation of strings
Concatenation of strings is done by using the CONCAT operator or the CONCAT built-in function
When the operands of the two strings are concatenated, the result of the expression is a string. The
operands of concatenation must be compatible strings.
SELECT LASTNAME CONCAT ’,’ CONCAT FIRSTNME
FROM EMP;
(or)
SELECT CONCAT(CONCAT(LASTNAME,’,’),FIRSTNME)
FROM EMP;
================
HAAS,CHRISTINE
THOMPSON,MICHAEL
KWAN,SALLY
STERN,IRVING
.
.
.
Accessing DB2 Data
Calculation of values in one or more columns
Calculations can be performed on numeric or date time data
SELECT EMPNO,
SALARY / 12 AS MONTHLY_SAL,
SALARY / 52 AS WEEKLY_SAL
FROM EMP
WHERE WORKDEPT = ’A00’;
SELECT YEAR(MAX(HIREDATE))
FROM EMP
WHERE WORKDEPT = ’A00’;
Example:
SELECT EMPNO, FIRSTNME, LASTNAME,
CASE
WHEN EDL<=12 THEN ’HIGH SCHOOL OR LESS’
WHEN EDL>12 AND EDL<=14 THEN ’JUNIOR COLLEGE’
WHEN EDL>14 AND EDL<=17 THEN ’FOUR-YEAR COLLEGE’
WHEN EDL>17 THEN ’GRADUATE SCHOOL’
ELSE ’UNKNOWN’
END
AS EDUCATION
FROM EMP
WHERE JOB=’FLD’;
Accessing DB2 Data
WHERE clause
The WHERE clause specifies a search condition. A search condition is the criteria that DB2 uses to select
rows.
A search condition consists of one or more predicates that are combined through the use of the logical
operators AND, OR and NOT.
Example:
SELECT HIREDATE, FIRSTNME, LASTNAME
FROM EMP
WHERE HIREDATE < ’2001-01-01’;
Accessing DB2 Data
Similarities of character data
The LIKE predicate can be used to specify a character string that is similar to the column value of rows that
are to be selected
A LIKE pattern must match the character string in its entirety
Use a percent sign (%) to indicate any string of zero or more characters
Use an underscore (_) to indicate any single character
Example:
SELECT FIRSTNME, LASTNAME, DEPT
FROM EMP
WHERE FIRSTNME LIKE ’D%’ AND LASTNAME LIKE ’B%’
Example:
SELECT DEPTNO, DEPTNAME
FROM DEPT
WHERE DEPTNAME LIKE ’%CENTER%’
Example:
SELECT DEPTNO, DEPTNAME
FROM DEPT
WHERE DEPTNO LIKE ’E_1’;
Accessing DB2 Data
Ranges of values
BETWEEN is used to select rows in which a column has a value within two limits
The limits are inclusive
NOT BETWEEN is used to select rows in which a column has a value that is outside the two limits
Example:
Example:
Example:
SELECT PROJNO, PROJNAME, RESPEMP
FROM PROJ
WHERE DEPTNO NOT IN (’C01’, ’E21’);
Accessing DB2 Data
ORDER BY clause
The ORDER BY clause is used to retrieve the rows in a specified order
A sort key can be a column name or an integer that represents the number of a column in the result table
The rows can be ordered in either ascending or descending order. Null values are included last in an
ascending sort and first in a descending sort
The ascending or descending order is specified by specifying ASC or DESC in the ORDER BY clause
Examples:
SELECT EMPNO, LASTNAME, HIREDATE SELECT JOB, EDL, LASTNAME
FROM EMP FROM EMP
WHERE DEPT = ’A00’ WHERE DEPT = ’A00’
ORDER BY HIREDATE ASC; ORDER BY JOB, EDL;
SELECT DEPT, LASTNAME, EMPNO SELECT EMPNO, SALARY, COMM, SALARY+COMM AS "TOTAL COMP"
FROM EMP FROM EMP
WHERE JOB = ’SLS’ WHERE SALARY+COMM > 40000
ORDER BY DEPT DESC; ORDER BY SALARY+COMM;
Accessing DB2 Data
GROUP BY clause
The GROUP BY clause is used to summarize group values
The GROUP BY can be used to group rows by the values of one or more columns and aggregate functions
can be applied to each group
Except for the columns that are named in the GROUP BY clause, the SELECT statement must specify any
other selected columns as an operand of one of the aggregate functions
Within the SELECT statement, the GROUP BY clause follows the FROM clause and any WHERE clause and it
precedes the HAVING and ORDER BY clauses
Examples:
SELECT DEPT, MIN(EDL), MAX(EDL)
FROM EMP
GROUP BY DEPT;
Examples:
SELECT DEPT, AVG(SALARY) AS AVG_SALARY
FROM EMP
GROUP BY DEPT
HAVING COUNT(*)> 1
ORDER BY DEPT;
Examples:
SELECT EMPNO FROM EMP
WHERE DEPT LIKE ’D%’
UNION
SELECT EMPNO FROM EMPPROJACT
WHERE PROJNO LIKE ’MA%’
(or)
SELECT DEPTNAME
FROM DEPT
WHERE DEPTNO IN
(SELECT WORKDEPT
FROM EMP
WHERE SALARY > 30000.00);
Accessing DB2 Data
Correlated subqueries
A correlated subquery is a subquery where in the nested SELECT statement refer back to the columns in the
previous SELECT statement
A non-correlated subquery is processed in the bottom-to-top fashion
A correlated subquery works in a top-bottom-top fashion
UPDATE NEWEMP
SET JOB = ’MGR’,
DEPT = ’E21’
WHERE EMPNO = ’100125’;
(or)
EXEC SQL
INCLUDE <copybookname>
END-EXEC.
For the above employee table, a host variable declaration looks like below. If DB2 tool DCLGEN is used, it will
automatically create this structure along with the table declaration.
01 EMPOYEE-RECORD.
05 HV-EMPID PIC X(10).
05 HV-EMPNAME PIC X(30).
05 HV-DEPARTMENT PIC X(2).
05 HV-SALARY PIC S9(8)V99 COMP-3.
05 HV-DESIGNATION PIC X(4).
DB2 Application Programming
SQL codes are numbers that indicate the results of SQL statements.
SQLCODE = 0 – Successful query execution
SQLCODE > 0 – Warning issued while executing the query
SQLCODE < 0 – Error occurred while executing the query
The SQL code is passed to a structure called the SQL Communication Area (SQLCA). The application can
retrieve the SQL code value from the SQLCODE field in the SQLCA.
The SQLCA also contains other information that is related to the SQL code
SQLCA is included in the WORKING-STORAGE SECTION
.........
EXEC SQL .........
EXEC SQL
INCLUDE SQLCA SELECT SALARY
END-EXEC. INTO :HV-SALARY
FROM EMPLOYEE
WHERE EMPNO = 115001
END-EXEC.
IF SQLCODE = 0
DISPLAY 'EMPLOYEE SALARY IS‘ HV-SALARY
ELSE
DISPLAY 'SQL failed with SQLCODE ‘ SQLCODE
END-IF.
.........
.........
DB2 Application Programming
COBOL-DB2 program preparation steps
Precompile
Pre-compiler separates out the DB2 SQL statements and COBOL statements from the COBOL-DB2 program and
generates timestamp tokens respectively
Pre-compiler checks for the syntax errors of DB2 statements. It does not check the syntax errors of COBOL
statements.
The main output from the pre-compiler is a database request module (DBRM)
A DBRM is a data set that contains SQL statements and host variable information that is extracted from the
source program during program preparation
The purpose of DBRM is to communicate the SQL requests to DB2 during the bind process
DSNHPC is utility used for the pre-compilation process
Bind
BIND is the process to create the optimized access path to retrieve the data from DB2 for the SQLs coded in the
program
BIND takes DBRM as input and generates the optimized access path with the help of optimizer which checks the
table statistics like the no. of columns, no. of rows, etc.
Before the DB2 application can run, use the BIND command to bind the DBRM to a package. When the program
runs, DB2 uses the timestamp to verify that the program matches the correct plan or package
IKJEFT01 is used for the bind process
DB2 Application Programming
Compile, Link-Edit
The separated COBOL source program goes through the
compilation process to generate an object program, which then is
link-edited to build an executable load module
IGYCRCTL is the COBOL compiler
The load module is a program unit that is loaded into the main
storage for program execution
IEWL is the utility program used for the link-edit process to
generate the load module
Open Cursor
Before a cursor is used, it must be opened using the OPEN statement
The OPEN statement prepares the SELECT for execution
EXEC SQL
OPEN STUDCUR
END-EXEC.
Cursors
Fetch Cursor
The FETCH statement is used to retrieve one row at a time
EXEC SQL FETCH STUDCUR
INTO :WS-STUDENT-ID, :WS-STUDENT-NAME, :WS-STUDENT-ADDRESS
END-EXEC.
Close Cursor
The CLOSE statement is used to close the cursor
It is recommended to explicitly close the cursor, when the cursor usage is completed
EXEC SQL
CLOSE STUDCUR
END-EXEC
Cursors
Cursors
Isolation Levels
Isolation Level Description
Cursor Stability (CS) The CS isolation level allows maximum concurrency with data integrity. The CS
fetches only the committed rows for the program to access. This is the default
isolation level. Under CS isolation, a transaction holds locks only on its uncommitted
changes and on the current row of each of its cursors. As soon as the program shifts
to the next row, the lock in the previous row gets released.
Uncommitted Read (UR) The UR isolation level is used in SQL statements meant for read-only purpose. There
is no lock placed on a row/record and it fetches the committed as well as
uncommitted rows from other programs or transactions.
Read Stability (RS) The RS isolation level allows the application to read the same pages or rows more
than once and prevents updates or deletes to qualifying rows by other processes.
The lock is retained until the entire processing is completed. Other applications can
insert or update rows that did not satisfy the search condition of the original
application.
Repeatable Read (RR) The RR isolation level allows the application to read the same pages or rows more
than once without allowing any update, insert or delete operations by other
processes. All accessed rows or pages are locked even if they do not satisfy the
predicate.
Unit of Work
A unit of work (or logical unit of work) is a recoverable sequence of operations within an application process
A unit of work is initiated when an application process is initiated and ended by a commit operation, a full
rollback operation or the end of the application process
The initiation and termination of a unit of work define the points of consistency within an application
process. A point of consistency is a claim by the application that the data is consistent.
Example
A banking transaction might involve the transfer of funds from one account to another. Such a transaction
would require that these funds be subtracted from the first account, and added to the second. Following
the subtraction step, the data is inconsistent. Only after the funds have been added to the second account
is consistency re-established. When both steps are complete, the commit operation can be used to end the
unit of work, thereby making the changes available to other application processes.
Locking, Commit, Rollback, Savepoint
Locking
More than one application process might request access to the same data at the same time. Locking is
used to maintain data integrity under such conditions, preventing two or more application processes
from updating the same row of data simultaneously.
Commit
The COMMIT statement terminates a unit of work and commits the database changes that were made by
that unit of work
Rollback
The ROLLBACK statement is used to back out the database changes that were made within a unit of work
or a savepoint
Savepoint
The SAVEPOINT statement is used to set a savepoint within a transaction
Locking, Commit, Rollback, Savepoint
Rollback all changes
Utility Description
LOAD Loads data into one or more tables of a table space. It loads records into the tables
and builds or extends any indexes that are defined on them.
UNLOAD Copies data from one or more table spaces to sequential datasets in external formats.
REORG INDEX Reorganizes an index space to improve access performance and reclaim fragmented
space
REORG TABLESPACE Reorganizes a table space to improve performance and to reclaim fragmented space
RUNSTATS Gathers statistics for table spaces, indexes and partitions and records these statistics
in the DB2 catalog. DB2 uses these statistics to select the most efficient access paths
for the queries.
COPY Copies table spaces, index spaces, partitions to be used for recovery. These copies are
called image copies. It can be either a full image copy or an incremental image copy.
DB2 Error Codes