0% found this document useful (0 votes)
12 views74 pages

DB2 For z/OS

DB2 for z/OS is a relational database management system that allows users to create and manage databases using SQL, supporting both relational and non-relational structures. It includes features like table spaces and index spaces for data organization, and various constraints to maintain data integrity. The document also outlines the differences between file systems and DBMS, data types, null values, default values, primary and foreign keys, and constraints in DB2.

Uploaded by

Richard Benjamin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views74 pages

DB2 For z/OS

DB2 for z/OS is a relational database management system that allows users to create and manage databases using SQL, supporting both relational and non-relational structures. It includes features like table spaces and index spaces for data organization, and various constraints to maintain data integrity. The document also outlines the differences between file systems and DBMS, data types, null values, default values, primary and foreign keys, and constraints in DB2.

Uploaded by

Richard Benjamin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 74

DB2 for z/OS

File System vs DBMS

File System DBMS


A file system is a software that manages and A DBMS is a software application that is used for
organizes the files in a storage medium. It controls accessing, creating and managing databases
how data is stored and retrieved.

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

CREATE TABLE table_name (


columns definition,
primary key/foreign key definition,
[LIKE reference table name])
IN databasename.tablespace name;
Table
CREATE TABLE DEPT CREATE TABLE EMPLOYEE
(DNO INTEGER NOT NULL, (EMPNO CHAR(6) NOT NULL,
DSTART DATE NOT NULL, FIRSTNME VARCHAR(12) NOT NULL,
DEND DATE NOT NULL, LASTNAME VARCHAR(15) NOT NULL,
DNAME VARCHAR(30), DEPT CHAR(3) ,
PRIMARY KEY DNO) HIREDATE DATE ,
IN DB.TS1; JOB CHAR(8) ,
EDL SMALLINT ,
SALARY DECIMAL(9,2) ,
CREATE TABLE EMP COMM DECIMAL(9,2) ,
(ENO INTEGER NOT NULL, PRIMARY KEY (EMPNO))
ESTART DATE NOT NULL, IN MYDB.MYTS;
EEND DATE NOT NULL,
EDEPT INTEGER,
FOREIGN KEY (EDEPT)
REFERENCES DEPT(DNO) CREATE TABLE EMPLOYEE2 LIKE EMPLOYEE
IN DB.TS2;
DB2 – Data Types
Data Type Description
CHAR(n) Fixed length string between 1 and 255 bytes. Default length is 1.
VARCHAR(n) Variable length string with a maximum length of n bytes. The maximum length is 32704.
SMALLINT 2-byte integer. holds values between + and – 32KB
INTEGER 4-byte integer; holds values between + and - 2 GB
DECIMAL(p,s) Decimal number; holds maximum 31 digits; p is the precision that is the total number of digits and s is the scale which
is the number of digits after the decimal point.
REAL/DOUBLE Single precision floating-point (4 bytes)/double-precision floating-point (8 bytes)
BINARY Fixed length binary up to 255 bytes. Default length is 1.
DATE A date is a three-part value representing a year, month, and day in the range of 0001-01-01 to 9999-12-31.
TIME A time is a three-part value representing a time of day in hours, minutes, and seconds, in the range of 00.00.00 to
24.00.00.
TIMESTAMP A timestamp is a seven-part value representing a date and time by year, month, day, hour, minute, second, and
microsecond, in the range of 0001-01-01-00.00.00.000000000 to 9999-12-31-24.00.00.000000000 with nanosecond
precision.
XML pureXML support to store XML documents
ROWID Uniquely identifies rows in a DB2 system
Null Values
 DB2 uses a special value indicator – the null value to stand for an unknown or missing value.
 A null value is a special value that DB2 interprets to mean that no data is present
 DB2 allows any column to contain null values. Users can create rows in the table without providing a value for the
column.
 Using NOT NULL clause enables to disallow null values in the column. Primary keys must be defined as NOT NULL
Default Values
 The DEFAULT clause is used to define default values for columns
 If a column is defined as NOT NULL WITH DEFAULT or if NOT NULL is not specified, DB2 stores a default value for a column
whenever an insert or load does not provide a value for that column
 If a column is defined as just NOT NULL, DB2 does not supply a default value
 DB2 generates a default value for ROWID columns
 DB2 determines default values for columns that users define with NOT NULL WITH DEFAULT, but for which no specific
value is specified as shown in the below table
Data Types Default Value
SMALLINT, INTEGER, 0
Example: If you want a record of each user who inserts any row DECIMAL, REAL, DOUBLE
of a table, define the table with two additional columns: CHAR, BINARY Blanks
PRIMARY_ID CHAR(8) WITH DEFAULT USER, VARCHAR Empty String
SQL_ID CHAR(8) WITH DEFAULT CURRENT SQLID DATE CURRENT DATE
TIME CURRENT TIME
TIMESTAMP CURRENT TIMESTAMP
ROWID DB2-generated
Primary Key
 A primary key of a table is a column or group of columns whose values uniquely identify every row in the table
 Primary key cannot contain null values
 A table cannot have more than one primary key
 Primary key on a table is optional
 To define a primary key on a table, the PRIMARY KEY constraint is used
 Primary keys can be defined in CREATE TABLE or ALTER TABLE statements
 When a primary key constraint is created on a table, DB2 automatically creates a unique index on the primary key
columns. This unique index is known as the primary index.
 A primary key can be defined on one or more columns. A primary key that includes two or more columns is called a
composite key
Primary Key

CREATE TABLE table_name ( ALTER TABLE table_name


pk_column data-type NOT NULL PRIMARY KEY, PRIMARY KEY (primary_key_columns);
...
);

CREATE TABLE table_name (


pk_column1 data-type NOT NULL,
pk_column2 data-type NOT NULL,
...,
PRIMARY KEY(pk_column1,pk_column2,...)
);
Foreign key
 A foreign key is a key that is specified in the definition of a referential constraint in a CREATE TABLE or ALTER TABLE
statement
 Unlike primary key, a foreign key does not require an index on its underlying column or columns
 A table can have zero or more foreign keys

 Each table has a primary key:


 DEPTNO in the DEPT table
 EMPNO in the EMP table
 Each table has a foreign key that establishes a relationship between
the tables:
 The values of the foreign key on the DEPT column of the EMP
table match values in the DEPTNO column of the DEPT table
 The values of the foreign key on the MGRNO column of the DEPT
table match values in the EMPNO column of the EMP table when
an employee is a manager
DB2 – Constraints
 Constraints are rules that control values in columns to prevent duplicate values or set restrictions on data added to a
table
 Constraints fall into the below types
 NOT NULL Constraints
 Unique Constraints
 Primary Key Constraints
 Referential Constraints
 Check Constraints
NOT NULL Constraints
 NOT NULL constraints prevent null values from being entered into a column
 By default, all of the built-in data types support the presence of null values
 The NOT NULL constraint is used to ensure that a given column of a table is never assigned the null value
 Once a NOT NULL constraint is defined on a particular column, any insert or update operation that attempts to place a
null value in that column will fail
Unique Constraints
 A unique constraint is a rule that the values in a column are unique and not null for all rows in the table
 Unique constraints are optional and can be defined in the CREATE TABLE or ALTER TABLE statements with the PRIMARY
KEY clause or the UNIQUE clause
 The columns specified in a unique constraint must be defined as NOT NULL
 A unique index enforces the uniqueness of the key during changes to the columns of the unique constraint
Referential Constraints
 A referential constraint is the rule that the non-null values of a foreign key are valid only if they also appear as values of
the parent key
 The table that contains the parent key is called the parent table of the referential constraint and the table that contains
the foreign key is a dependent of that table
 Referential constraints are defined using CREATE TABLE and ALTER TABLE statements
 When foreign key contains multiple columns, the corresponding primary key must be a composite key. The number of
foreign key columns must be the same as the number of columns in the parent key and the data types of the
corresponding columns must be compatible.
 A table can be a dependent of itself and it is called as a self-referencing table. To enforce the self-referencing constraint,
DB2 requires that a foreign key be defined.
Referential Constraints
Referential Constraints
Check Constraints
 Check constraints are used to ensure that only values from the domain for the column or attribute are allowed
 One advantage of using check constraints is that programmers do not need to develop, test and maintain application
code that performs these checks
 Check constraints are defined using the CREATE TABLE or ALTER TABLE statement
 DB2 automatically enforces all check constraints for a table when an UPDATE statement is used to change a row in the
table. If the intended update violates any check constraint that is defined on that table, DB2 does not update the row.
 Example: Ensure that each value in the SALARY column of the EMPLOYEE table contains more than a certain minimum
amount i.e., 10000 as shown in the below CREATE TABLE statement
 DB2 enforces a check constraint by applying the relevant condition to each row that is inserted, updated or loaded. An
error occurs if the result of the condition is false for any row and the relevant operation is not performed.
CREATE TABLE EMPLOYEE
(EMPNO CHAR(6) NOT NULL,
FIRSTNME VARCHAR(12) NOT NULL,
LASTNAME VARCHAR(15) NOT NULL,
DEPT CHAR(3) ,
HIREDATE DATE ,
JOB CHAR(8) ,
EDL SMALLINT ,
SALARY DECIMAL(9,2) CHECK (SALARY > 10000),
COMM DECIMAL(9,2) ,
PRIMARY KEY (EMPNO))
IN MYDB.MYTS;
Check Constraints
 Example

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.

INSERT INTO NEWEMP


(EMPNO, FIRSTNME, LASTNAME, DEPT, JOB, SALARY, COMM)
VALUES (’100101’, ’JOHN’, ’HAVARD’,’100’, ’HR’, 70000.00, 7000.00);

The below INSERT statement fails because $15000 commission is higher than the $10000 salary. The INSERT statement
violates the check constraint on NEWEMP.

INSERT INTO NEWEMP


(EMPNO, FIRSTNME, LASTNAME, DEPT, JOB, SALARY, COMM)
VALUES (’100109’, ’LAILA’, ’DENVER’,’100’, ’PM’, 10000.00, 15000.00 );
Check Constraints
 Example
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’ and ‘100’ inclusive

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’;

 Example: Add a constraint to an already existing table named EMPLOYEE


ALTER TABLE EMPLOYEE
ADD CONSTRAINT BONUS_LT_SALARY
CHECK (BONUS < SALARY);
Check Constraints
 Example
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’ and ‘100’ inclusive

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’;

 Example: Add a constraint to an already existing table named EMPLOYEE


ALTER TABLE EMPLOYEE
ADD CONSTRAINT BONUS_LT_SALARY
CHECK (BONUS < SALARY);
Indexes
 An index is an ordered set of pointers to rows of a table
 DB2 uses indexes to improve performance and ensure uniqueness
 The main purpose of an index is to improve performance for access to the data
 An index is stored separately from the data in a table. Each index is physically stored in its own index space.
 An index is created using the CREATE INDEX statement. DB2 builds this structure and maintains it
automatically
 A primary index is an index that ensures the value in a particular column or set of columns is unique . A table
can have more than one unique indexes.
 A primary index is a unique index on the primary key of the table. Each table can have only one primary
index.
Views
 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
 You can create a view that:
 Combines data from different base tables
 Is based on other views or on a combination of views and tables
 Omits certain data, thereby shielding some table data from users
 A view is created using the CREATE VIEW statement
 When a view is defined, DB2 stores the definition of the view in the DB2 catalog. DB2 does not store any data
for the view itself, because the data exists in the base tables or tables.
 The figure shows a view of the EMP table that omits sensitive
employee information and renames some of the columns

CREATE VIEW EMPINFO (EMPLOYEE,FIRSTNAME,LASTNAME,TEAM,JOBTITLE)


AS SELECT EMPNO,FIRSTNME,LASTNAME,DEPT,JOB
FROM EMP;
Accessing DB2 Data
 Data from a DB2 table can be retrieved using the SQL SELECT statement
 The data that is retrieved through SQL is also in the form of a table that has rows and columns and is often
referred to as the result set
 Selection of some columns
Select the columns that you want by specifying the name of each column. All columns appear in the order
that is specified and not in their order in the table.
SELECT MGRNO, DEPTNO
FROM DEPT
WHERE ADMRDEPT = ’A00’;

The result table looks like

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’;

The result table looks like

DEPTNO DEPTNAME MGRNO ADMRDEPT LOCATION


====== ======== ===== ======== ========
A00 SPIFFY COMPUTER SERVICE DIV. 000010 A00 --------
B01 PLANNING 000020 A00 --------
C01 INFORMATION CENTER 000030 A00 --------
D01 DEVELOPMENT CENTER ------ A00 --------
E01 SUPPORT SERVICES 000050 A00 --------
Accessing DB2 Data
 Elimination of duplicate rows
The DISTINCT keyword is used to remove duplicate rows
from the result table so that each row contains unique
data

SELECT DISTINCT ADMRDEPT


FROM DEPT;

The result table looks like

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;

The result table looks like

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;

The result table looks like

================
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’;

The result table looks like

EMPNO MONTHLY_SAL WEEKLY_SAL


===== =========== ==========
000010 4395.83333333 1014.42307692
000110 3875.00000000 894.23076923
000120 2437.50000000 562.50000000
Accessing DB2 Data
 Calculation of aggregate values
An aggregate function is an operation that derives its result by using values from one or more rows
An aggregate function is also known as a column function
The argument of an aggregate function is a set of values
The functions like COUNT ignore nulls in the values on which they operate

Aggregate Function Description SELECT SUM(SALARY) AS SUMSAL,


MIN(SALARY) AS MINSAL,
SUM Returns the total value AVG(SALARY) AS AVGSAL,
MAX(SALARY) AS MAXSAL,
MIN Returns the minimum value COUNT(*) AS CNTSAL
FROM EMP
MAX Returns the maximum value WHERE WORKDEPT = ’A00’;
AVG Returns the average value
COUNT Returns the number of selected rows SELECT COUNT(*)
FROM EMP;
TIMESTAMP CURRENT TIMESTAMP
ROWID DB2-generated SELECT COUNT(DISTINCT JOB)
FROM EMP;
Accessing DB2 Data
 Scalar Functions
Like an aggregate function, a scalar function produces a single value. Unlike the argument of an aggregate
function, an argument of a scalar function is a single value
DB2 offers many different scalar functions
Scalar Functions
ABS DAYOFYEAR LAST_DAY REPEAT TRANSLATE
ADD_MONTHS DAYS LEFT REPLACE TRUNCATE
CEIL DECIMAL LENGTH RIGHT UPPER/UCASE
CHAR DIGITS LOCATE ROUND VALUE
COALESCE DOUBLE/FLOAT LOWER/LCASE RTRIM VARCHAR
CONCAT FLOOR LTRIM SECOND WEEK
DATE HOUR MINUTE SIGN YEAR
DAY IFNULL MOD SMALLINT
DAYOFMONTH INTEGER MONTH SUBSTR
DAYOFWEEK JULIAN_DAY REAL TIME
Accessing DB2 Data
 Scalar Functions
SELECT YEAR(HIREDATE) AS HIREYEAR
FROM EMP
WHERE WORKDEPT = ’A00’;

The result table looks like


HIREYEAR
========
1965
1958
1963

SELECT YEAR(MAX(HIREDATE))
FROM EMP
WHERE WORKDEPT = ’A00’;

The result table looks like


========
1965
Accessing DB2 Data
 CASE expression
A CASE expression allows to select an expression based on the evaluation of one or more conditions
CASE expression
WHEN expression_1 THEN result_1
WHEN expression_2 THEN result_2
...
WHEN expression_n THEN result_n
[ ELSE else_result ]
END

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.

A variety of different comparison


operators in the predicate of a WHERE
clause can be used as listed in the figure
Accessing DB2 Data
 Retrieving and excluding rows with null values
A null value indicates the absence of a column value in a row and it is not the same as zero or blanks.
One can retrieve or exclude rows that contain a null value in a specific row
To retrieve rows that contain a null value in a specific column, specify
WHERE column-name is NULL
To exclude rows that contain a null value in a specific column, specify
WHERE column-name is NOT NULL
Equal sign cannot be used to retrieve rows that contain a null value
WHERE column-name = NULL is not allowed
Accessing DB2 Data
 Equalities and inequalities
An equal sign (=), various inequality symbols (<> < <= > >=) and the NOT keyword can be specified in
search conditions in the WHERE clause
Example:
SELECT FIRSTNME, LASTNAME
FROM EMP
WHERE DEPT = ’A00’;

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:

SELECT FIRSTNME, LASTNAME


FROM EMP
WHERE YEAR(HIREDATE) BETWEEN 1950 and 1980
Accessing DB2 Data
 Values in a list
The IN predicate is used to select each row that has a column value that is equal to one of several listed
values
The list of values is enclosed in parentheses and separated by commas

Example:

SELECT DEPTNO, MGRNO


FROM DEPT
WHERE DEPTNO IN (’B01’, ’C01’, ’D11’);

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;

SELECT DEPT, JOB, AVG(SALARY) AS AVG_SALARY


FROM EMP
WHERE DEPT IN (’D11’, ’E21’)
GROUP BY DEPT, JOB;
Accessing DB2 Data
 Specifying search conditions
The HAVING clause is used in a variety of ways to specify search conditions
The HAVING clause acts like a WHERE clause for groups and it can contain the same kind of search
conditions that like in a WHERE clause
The HAVING COUNT(*) > 1 clause ensures that only departments with more than one member are
displayed

Examples:
SELECT DEPT, AVG(SALARY) AS AVG_SALARY
FROM EMP
GROUP BY DEPT
HAVING COUNT(*)> 1
ORDER BY DEPT;

SELECT DEPT, AVG(SALARY) AS AVG_SALARY,


MIN(EDL) AS MIN_EDL
FROM EMP
WHERE HIREDATE>= ’1990-01-01’ AND DEPT IN (’A00’, ’D11’)
GROUP BY DEPT
HAVING MIN(EDL)>= 14;
Accessing DB2 Data
 Merging lists of values
There are several ways to use the UNION keyword for merging list of values
A union is an SQL operation that combines the results of two SELECT statements to form a single result
table
Using only UNION keyword, distinct rows are obtained in the result table and UNION ALL is used to obtain
all rows including duplicates

Examples:
SELECT EMPNO FROM EMP
WHERE DEPT LIKE ’D%’
UNION
SELECT EMPNO FROM EMPPROJACT
WHERE PROJNO LIKE ’MA%’

SELECT EMPNO FROM EMP


WHERE DEPT LIKE ’D%’
UNION ALL
SELECT EMPNO FROM EMPPROJACT
WHERE PROJNO LIKE ’MA%’
Accessing DB2 Data
 Joining data from more than one table
The SELECT statement can retrieve and join column values from two or more tables into single row
DB2 supports inner joins and outer joins (left, right and full)
Inner Join
Combines each row of the left table with each row of the right table, keeping only the rows in which
the join condition is true
Outer Join
Includes the rows that are produced by the inner join plus the missing rows depending on the type of
the outer join

Type of Outer Join Description


Left Outer Join Includes the rows from the left table that were missing from the inner join
Right Outer Join Includes the rows from the right table that were missing from the inner join
Full Outer Join Includes the rows from both tables that were missing from the inner join
Accessing DB2 Data
 Joining data from more than one table
Accessing DB2 Data
 Joining data from more than one table

Example of Inner Join


SELECT PART, SUPPLIER, PARTS.PROD#, PRODUCT
FROM PARTS, PRODUCTS
WHERE PARTS.PROD# = PRODUCTS.PROD#;

(or)

SELECT PART, SUPPLIER, PARTS.PROD#, PRODUCT


FROM PARTS INNER JOIN PRODUCTS
ON PARTS.PROD# = PRODUCTS.PROD#;

Either of these statements gives this result:


PART SUPPLIER PROD# PRODUCT
======= ============ ===== =========
WIRE ACWF 10 GENERATOR
MAGNETS BATEMAN 10 GENERATOR
BLADES ACE_STEEL 205 SAW
PLASTIC PLASTIK_CORP 30 RELAY
Accessing DB2 Data
 Joining data from more than one table

Example of Left Outer Join


SELECT PART, SUPPLIER, PARTS.PROD#, PRODUCT, PRICE
FROM PARTS LEFT OUTER JOIN PRODUCTS
ON PARTS.PROD#=PRODUCTS.PROD#
AND PRODUCTS.PRICE>10.00;

The result table looks like this


PART SUPPLIER PROD# PRODUCT PRICE
======= ============ ===== ========= =====
WIRE ACWF 10 GENERATOR 45.75
MAGNETS BATEMAN 10 GENERATOR 45.75
OIL WESTERN_CHEM 160 --------- -----
BLADES ACE_STEEL 205 SAW 18.90
PLASTIC PLASTIK_CORP 30 --------- -----
Accessing DB2 Data
 Joining data from more than one table

Example of Right Outer Join


SELECT PART, SUPPLIER, PRODUCTS.PROD#, PRODUCT, PRICE
FROM PARTS RIGHT OUTER JOIN PRODUCTS
ON PARTS.PROD# = PRODUCTS.PROD#
WHERE PRODUCTS.PRICE>10.00;

The result table looks like this


PART SUPPLIER PROD# PRODUCT PRICE
======= ============ ===== ========== =====
MAGNETS BATEMAN 10 GENERATOR 45.75
WIRE ACWF 10 GENERATOR 45.75
BLADES ACE_STEEL 205 SAW 18.90
Accessing DB2 Data
 Joining data from more than one table

Example of Full Outer Join


SELECT PART, SUPPLIER, PARTS.PROD#, PRODUCT
FROM PARTS FULL OUTER JOIN PRODUCTS
ON PARTS.PROD# = PRODUCTS.PROD#;

The result table looks like this


PART SUPPLIER PROD# PRODUCT
======== ============ ===== ===========
WIRE ACWF 10 GENERATOR
MAGNETS BATEMAN 10 GENERATOR
OIL WESTERN_CHEM 160 -----------
BLADES ACE_STEEL 205 SAW
PLASTIC PLASTIK_CORP 30 RELAY
------- ------------ ----- SCREWDRIVER
Accessing DB2 Data
 Subqueries
A subquery is a nested SQL statement that contains a SELECT statement within the WHERE or HAVING
clause of another SQL statement
A subquery enables a user to base the search criteria of one SELECT statement on the results of another
SELECT statement

SELECT EMPNO, LASTNAME, COMM SELECT EMPNO, LASTNAME


FROM EMP FROM EMP
WHERE EMPNO IN WHERE WORKDEPT =
(SELECT EMPNO (SELECT DEPTNO
FROM EMPPROJACT FROM DEPT
WHERE PROJNO = ’IF2000’); WHERE DEPTNAME = 'PLANNING');

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

SELECT A.WORKDEPT, A.EMPNO, A.FIRSTNME, A.MIDINIT,


A.LASTNAME, A.SALARY
FROM EMP A
WHERE A.SALARY >
(SELECT AVG(B.SALARY)
FROM EMP B
WHERE A.WORKDEPT = B.WORKDEPT)
ORDER BY A.WORKDEPT, A.EMPNO;
Modifying DB2 Data
 SQL statements can be used to add, modify, remove data in existing tables
 The INSERT, UPDATE and DELETE statements are used to manipulate DB2 data
 Any modifications must maintain the integrity of table relationships. DB2 ensures that an insert, update or
delete operation does not violate any referential constraint or check constraint that is defined on a table.

INSERT INTO NEWDEPT (DEPTNO, DEPTNAME, MGRNO, ADMRDEPT)


VALUES (’E31’, ’PUBLISHING’, ’000020’, ’D11’);

UPDATE NEWEMP
SET JOB = ’MGR’,
DEPT = ’E21’
WHERE EMPNO = ’100125’;

DELETE FROM NEWEMP


WHERE EMPNO = ’000060’;
Submitting SQL statements to DB2
 There are different methods to send SQL statements to DB2
 Interactive SQL: Refers to SQL statements that are submitted to DB2 by using SPUFI (SQL Processor Using
File Input) or the command line processor or by using query tools like DB2 Query Management Facility
(QMF)
 Static SQL: The source form of a static SQL is embedded within an application program written in a host
language such as COBOL. The statement is prepared before the program is executed and the operational
form of the statement persists beyond the execution of the program.
 Dynamic SQL: Dynamic SQL is used when you do not know the content of an SQL statement when you
write the program or before you run it
Submitting SQL statements to DB2
DB2 Interactive (DB2I) is a set of ISPF panels to work interactively with many different aspects of DB2
DB2 Application Programming
 Embedded SQL statements are used in COBOL programs to perform standard SQL operations. They are
enclosed within EXEC SQL and END-EXEC statements
 Embedded SQL statements are preprocessed by the SQL processor before the application program is
compiled
 All the tables that are used in a program must be declared in the WORKING-STORAGE SECTION which is done
by the INCLUDE statement
 All SQL statements other than INCLUDE and DECLARE TABLE must appear in the PROCEDURE DIVISION
 Host variables are application program variables that contain the data that is exchanged with the DB2 table.
Host variables are prefixed with a colon (:) when used with SQL statements.
 Indicator variables are application program variables whose values denote whether there is data in the host
variables
Less than zero – the column value is null
Zero – the column value is non-null
greater than zero – the retrieved value is truncated. The value in the indicator variable is the original length of the value.
DB2 Application Programming
 Declare the table structure in WORKING-STORAGE SECTION or create a copybook using DCLGEN to generate the
declaration and include that copybook
EXEC SQL
DECLARE EMPLOYEE
(EMPID CHAR(10) NOT NULL,
EMPNAME CHAR(30) NOT NULL,
DEPARTMENT CHAR(2) NOT NULL,
SALARY DECIMAL(10,2) NOT NULL,
DESIGNATION CHAR(4) NOT NULL)
END-EXEC.

(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

Sample JCL to execute a COBOL program


//SAMPLE JOB(TESTJCL,XXXXXX),CLASS=A,MSGCLASS=X
//STEP001 EXEC PGM=IKJEFT01
//STEPLIB DD DSN=SN410542.TEST.DBRMLIB,DISP=SHR
//SYSPRINT DD SYSOUT=*
//SYSUDUMP DD SYSOUT=*
//SYSOUT DD SYSOUT=*
//SYSTSIN DD *
DSN SYSTEM(SSID)
RUN PROGRAM(PGMA) PLAN(PLANNAME)
END
/*
DB2 Application Programming
 Package
 A package contains only one DBRM
 Packages are produced during program preparation
 Packages make application programs more flexible and easier to maintain
 A package is non executable, which means it cannot be used with the COBOL load module to run the application
program
 In order to make a package to be executed, it has to be binded to a plan
 A package is created by using the DB2 command BIND PACKAGE
 Plan
 A plan contains one or more DBRMs or packages or a combination of both
 A plan is executable, which means it can be executed with the COBOL load module to run the application program
 A plan is created by using the DB2 command BIND PLAN

The figure shows an application plan that contains two packages.


Suppose that you decide to change the SELECT statement in
package AA to select data from a different table. In this case, you
need to bind only package AA again and not package AB.
Cursors
 Cursors are used to handle multiple row selections at a time. It retrieves and process one row from a set of
rows retrieved by the application program.
 Cursors can be used to fetch, update or delete one or more rows of a table, but it cannot be used to insert a
row into a table
 There are two types of cursors based on how the cursor is used in the program
 Read-Only Cursor
 The cursor is used for only retrieving the data from tables and it cannot be used to perform any
update operation on the table
 The cursor will be declared with FOR FETCH ONLY. It is the default.
 Updatable Cursor
 The cursor is used for only update of the table after retrieving the data from the table
 The cursor will be declared with FOR UPDATE OF
 Positioned UPDATE and positioned DELETE are allowed with these cursors
 The WHERE CURRENT OF clause will point to the most recently fetched row of the cursor
Cursors
 The different cursor operations include the following:
 Declare Cursor
 Cursor declaration can be done either in the WORKING-STORAGE SECTION or PROCEDURE DIVISION
 The DECLARE statement is used to declare a cursor and is a non-executable statement
EXEC SQL
DECLARE STUDCUR CURSOR FOR
SELECT STUDENT-ID, STUDENT-NAME, STUDENT-ADDRESS
FROM STUDENT
WHERE STUDENT-ID >:WS-STUDENT-ID
END-EXEC

 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

Rollback selected changes using savepoints


Deadlock
 A deadlock occurs when two or more application processes each hold locks on resources that the others need
and without which they cannot proceed
 When a deadlock arises, DB2 errors out with SQLCODE -911
 Example
User A has a lock on resource R1 and requires lock on resource R2. User B has lock on resource R2 and
requires lock on resource R1. This situation is called Deadlock.
DB2 Utilities

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

Error Code Description


000 Success
+100 Rows not found in the table to select that satisfies the condition (or)
End of the rows fetched in a cursor
-502 Program tries to fetch the data for a particular cursor that is not opened
-503 Program tries to open a cursor that is already opened
-803 Program tries to insert a row which is already existing with the same key
-805 When the plan not found or not available
-811 SELECT statement retrieving more than one row from the table
-818 Timestamp mismatch error
-904 Resource not available
-911 Deadlock with timeout
-922 Authorization failure

You might also like