You are on page 1of 74

School of MAINFRAMES

Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

DB2

1
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

2
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Data
Data consists of facts and Information about people, objects, events or any other items.

Database
A database is a tool for storing and organizing information (data).
Ex of database is Retail, Insurance, Banking and Financial.

DBMS
A Database Management System (DBMS) is software packages designed to store and manage
databases and also a computerized record-keeping system.

Types of Databases (or Models)

1. Hierarchical Model
2. Network Model
3. Relational Model

Hierarchical Model
Relation between entities is established using parent-child relationship inverted tree structure.
This is the first logical model of DBMS. Data stored in the form of segments.
Example - IMS

Network Model
Any entity can be associated with any other entity. So distinguishing between parent and child is
not possible. This is a linked structure model. Data stored in record and different record types are
linked by SETS.
Example - IDMS

Relational Model
Data stored in the form of tables consists of multiple rows (Tuples) and columns (Attributes).
Examples - DB2, Oracle, Sybase, Ingres etc.

Relational Concepts

Relation: A table or File


Tuple: Row contains an entry for each attribute
Attributes: Columns or the characteristics that define the entity
Domain: A range of values (or Pool)
Entity: Some object about which we wish to store information
Null: Represents an unknown/empty value
Atomic Value: Smallest unit of data; the individual data value
Candidate key: Some attribute (or a set of attributes) that may uniquely Identify each row (tuple)
in the relation (table)
Primary key: The candidate key that is chosen for primary attributes to uniquely identify each
row.
Alternate key: The remaining candidate keys that were not chosen as primary key
Foreign key: An attribute of one relation that might be a primary key of another relation.

3
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Advantages of DB2 over VSAM

Feature DB2 VSAM

1.Hardware Independence PC to mainframe Only Mainframe

2.Security High degrees of security at table and views Only at region level

3.Concurrency Multiple programs or users can update a table It is possible in online but not in
both in online and batch batch

4.Referential constraints Set Null, Restrict, Cascade is possible No such a facility. It is developers
cannot insert a foreign key if that has no responsibility
reference in parent

5.Independency When a new column is added to a table no Recompile all the programs if the
change in the program when the views are used filler is not there for the new field

6.Restart, in the abend time Program can be restarted from the last Bring corrupted files to original state
commit record. by del/def and load from backup.
Then Restart from the top.

7.Backup Incremental backup No incremental backup


Parallel backup Downtime needed

8.Disaster Recovery Supported by DB2 Part of DASD recovery

9.Improved performance Indexes can be used for the faster retrieval No such a facility

10.Data retrieval Selection criteria on different tables and on One record at a time, one file at a
different columns time.

11.Column functions Group Average, sum, min max, group by, having No such a facility
Functions

12.Program Preparation Extra preparation is required. Extra procedure It is native to COBOL, easy to write,
is required to run no extra coding is required, no extra
preparation is required

13.Occurs on repeated fields Occurs cannot be declared Occurs can be used and it reduces
coding

Variable length records are created


14.Variable length records Variable length fields are available but when different layouts are stored or
Variable length records are not available When occurs depending clause is
used

15.Different layouts It is not possible to store different layouts It is possible to store different layouts in a
in a single table single table

16.Maintenance Cost Costly cheaper

4
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

VSAM vs DB2

Object Creation

VSAM DB2
1.Create in Batch with IDCAMS 1.It is never created in batch
Create in foreground with FILE AID Create in SPUFI/QMF with SQL Query
Create in foreground with FILE AID DB2
2.Specify keys, space, cisz.... 2.No need to specify space
but no need to specify its layout But specify its columns and attributes

Copybook Creation

VSAM DB2
1.Create a copybook manually and 1.Create copybook with DCLGEN option
use it in the program with COPY. in DB2I and declare it with INCLUDE
(or)
Write its layout in the program
2.Supply copy library in the SYSLIB 2.Supply copy library in the SYSLIB of
of compile step Precompile step

How to use in program

VSAM DB2
1. Declare file in Select statement 1/2. Include copybook for table declaration
2. Declare layout in FD entry as well as host variable declaration
3. Declare status in WS 3. Include SQLCA for SQLCODE in WS
4. Open file with mode in PD 4. No need to open tables
5. Read/write/rewrite/start/read next 5. Use embedded sql statements for
file in PD select, insert, update, delete in PD
6. Close file in PD 6. No need to close table
7. Check status code after I-O operation 7. Check SQLCODE after execution of SQL Query
8. Direct relation is available between 8. Columns has to be mapped into host variables
file and its layout in the SQL statement

Program Preparation

VSAM DB2
1. VSAM files are native to COBOL 1. DB2 tables are not native to COBOL program.
programs. So it can be compiled So extra compilation procedure is required.
as a normal COBOL compilation.
2. Compile COBOL + VSAM program 2. Compile COBOL + DB2 program with the
with below steps. below steps.
Step1: Compile Step1: Precompile
Step2: Link Edit Step2: Compile
Step3: Link Edit
Step4: Bind package
Step5: Bind plan

5
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Test data preparation

VSAM DB2
1. Foreground 1. Foreground
a. File Aid for files a. File Aid for DB2
b. DITTO b. DB2 manager
2. Batch 2. Batch
Copy test data by using batch utility Copy test data by using batch utility
program IDCAMS From VSAM to VSAM program DSNUTILB from PS to DB2
From PS to VSAM
3. No such a facility 3. By executing Insert/Update from
SPUFI/QMF

Program execution with RUN JCL

VSAM DB2
//step1 exec pgm=PGM1 //step1 exec pgm=IKJEFT01
//steplib dd dsn=userid.loadlib1,disp=shr //*
//infile dd dsn=userid.infile,disp=shr //infile dd dsn=userid.infile,disp=shr
//agtmst dd dsn=userid.agtmst,disp=shr //outfile dd dsn=userid.outfile,
//outfile dd dsn=userid.outfile, // disp=(new,catlg,delete)
// disp=(new,catlg,delete), // unit=sysda,
// unit=sysda, // space=(cyl,(5,2),rlse),
// space=(cyl,(5,2),rlse), // dcb=(recfm=fb,lrecl=100,blksize=0)
// dcb=(recfm=fb,lrecl=100,blksize=0) //systsin dd *
DSN System(DB2T) -
Run Program(PGM1) Plan(PLAN1) -
Library(Userid.loadlib1)
/*

1.Program name is specified in PGM parameter 1. IKJEFT01 is specified in PGM parameter


2.VSAM file AGTMST is specified under program 2. No need to specify the tables in JCL

Normalization (1NF - 5NF)

It is done to bring the design of database to a standardized mode or (form)

1NF: All entities must have a unique identifier, or key, that can be composed of one or more
attributes. All attributes must be atomic and none repeating.
2NF: Partial functional dependencies removed - all attributes that are not a part of the key must
depend on the entire key for that entity.
3NF: Transitive dependencies removed - attributes that are not a part of the key must not depend
on any non-key attribute.
4NF: Multi valued dependencies removed.
5NF: Remaining anomalies removed.

6
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

STRUCTURE OF DB2

The elements of DB2 are divided into two broad categories.


1. Data structures
2. System structures

Data structures
Data structures contain user data and are accessed under user’s direction.
It consist of Databases,Db2 storage groups, Table spaces, Tables, Index spaces, indexes, Views,
Synonyms, Aliases.

System structures
System structures are controlled and accesses by DB2.
It consists of Db2 Catalog, Db2 Directory, Active and Archive logs, Buffer pools.

Databases:
DATABASE1

TABLESPACE 1

INDEX 1 TABLE 1 TABLE 2

INDEX 2

TABLESPACE 2

Database is a collection of a number of table spaces along with a set of index spaces.
A stored table and all it’s associated indexes must be in a single database.
When you create a table space or table and do not specify the database the object will be created
in the default database DSNDB04.

Db2 storage groups:


STORAGE GROUP 1
VOLUME 1 VOLUME 2

User and System Databases are physically stored in the datasets of specified storage groups.
Storage group is a set of volumes of direct access storage devices (DASD).Parts of single
database can be stored in different storage groups. Default storage group is SYSDEFLT.

7
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Table spaces:
Table space is made up of one or more VSAM linear datasets (LDS).where one or more tables are
stored. A table space is divided into 4k or 32k pages. A page is a unit of I/O transmission. A page
may contain one or more rows (max 127). A row must lie within a page.

TABLESPACE 1
TABLE 1

TABLE 2

SIMPLE SEGMENTED PARTITIONED

Simple Table space


Can contain more than one stored table. Depending on application, storing more than one Table
might enable faster retrieval for joins using these tables. Usually only one is preferred. This is
because a single page can contain rows from all tables defined in the database. LOAD with
replace option deletes all data.

Simple tablespace
Page1 Page2
-------------- --------------
| TBL1 ROW1 | | TBL1 ROW4 |
| TBL2 ROW1 | | TBL2 ROW3 |
| TBL3 ROW1 | | TBL3 ROW3 |
| TBL1 ROW2 | | TBL1 ROW5 |
| TBL1 ROW3 | | TBL2 ROW3 |
| TBL2 ROW2 | | TBL3 ROW4 |
| TBL3 ROW2 | | TBL3 ROW5 |
-------------- --------------

Segmented Table spaces


An contain more than one stored table, but in a segmented space. A ‘Segment’ consists of a
logically contiguous set of ‘n’ pages. Segsize parameter decides the allocation size for the
tablespace. Sequential access to a particular table is more efficient. Mass Delete is much more
efficient than in any other Tablespace. Reorganizing the tablespace will restore every table to its
clustered order. Lock Table on table locks only the table, not the entire tablespace . If a table is
dropped, the space for that table can be reclaimed with minimum reorg.
Segmented Tablespace
Segment1 Segment2
------------------------------------- -------------------------------------
| Page1 Page2 | | Page1 Page2 |
| ------------ ------------ | | ------------ ------------ |
| | TBL1 ROW1 | | TBL1 ROW8 | | | | TBL2 ROW1 | | TBL2 ROW8 | |
| | TBL1 ROW2 | | TBL1 ROW9 | | | | TBL2 ROW2 | | TBL2 ROW9 | |
| | TBL1 ROW3 | | TBL1 ROW10| | | | TBL2 ROW3 | | TBL2 ROW10| |
| | TBL1 ROW4 | | TBL1 ROW11| | | | TBL2 ROW4 | | TBL2 ROW11| |
| | TBL1 ROW5 | | TBL1 ROW12| | | | TBL2 ROW5 | | TBL2 ROW12| |
| | TBL1 ROW6 | | TBL1 ROW13| | | | TBL2 ROW6 | | TBL2 ROW13| |
| | TBL1 ROW7 | | TBL1 ROW14| | | | TBL2 ROW7 | | TBL2 ROW14| |
| ------------ ------------ | | ------------ ------------ |
------------------------------------- -------------------------------------

8
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Partitioned Tablespaces
Primarily used for Very large tables. Only one table in a partitioned TS; 1 to 64 partitions/TS .
Numpart parameter specifies the no. of partitions. It is partitioned in accordance with value
ranges for single or a combination of columns. Hence these column(s) cannot be updated
Individual partitions can be independently recovered and reorganized. Different partitions can be
stored on different storage groups for efficient access.
Partitioned Tablespace
Page1 Page2 Page3 Page4
------------ ------------ ------------ ------------
| TBL1 ROW1 | | TBL1 ROW8 | | TBL1 ROW15| | TBL1 ROW22|
| TBL1 ROW2 | | TBL1 ROW9 | | TBL1 ROW16| | TBL1 ROW23|
| TBL1 ROW3 | | TBL1 ROW10| | TBL1 ROW17| | TBL1 ROW24|
| TBL1 ROW4 | | TBL1 ROW11| | TBL1 ROW18| | TBL1 ROW25|
| TBL1 ROW5 | | TBL1 ROW12| | TBL1 ROW19| | TBL1 ROW26|
| TBL1 ROW6 | | TBL1 ROW13| | TBL1 ROW20| | TBL1 ROW27|
| TBL1 ROW7 | | TBL1 ROW14| | TBL1 ROW21| | TBL1 ROW28|
------------ ------------ ------------ ------------
One segmented tablespace is created for each table in many real applications.

Tables:
A relational database stores data in the form of tables. Table consists of a number of records.
Record contains Columns, Rows, Keys etc. Each record should be contained in a single page but
a table can be spread over pages.
For example SUPPLIER table looks like:
Each COLUMN contains some specific information about suppliers and each ROW contains all
the information about a particular supplier.
KEY COLUMNS

SNO SNAME STATUS CITY

ROWS S1 SMITH 20 LONDON


S2 JONES 10 PARIS
S3 BLAKE 30 PARIS
S4 CLARK 20 LONDON
S5 ADAMS 30 ATHENS

Views:
What is a View
• View is a subset of a table and it is created with a select query on a table
• View does not occupy any memory to store the data
Syntax:
CREATE VIEW view_name AS
SELECT columns
FROM table
WHERE predicates;

DROP VIEW view_name;

Ex:
Create View EMP_2011 as
SELECT * from emp
where emp_doj >= 20110101
and emp_doj <= 20111231;

9
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

SELECT *
from EMP_2011
where emp_status = 'A';

DROP VIEW EMP_2011;

Advantages of View
1. It is mainly used to restrict the table data from different users.
Views can limit the degree of exposure of a table or tables to the outer world.
Ex: Employee salary details can be hide from departments other than HR
2. Views can hide the complexity of data;
Ex: for example a view could appear as Sales2000 or Sales2001
3. Views can join and simplify multiple tables into a single virtual table
4. Views take very little space to store view definition
5. Views reduce future maintenance of the program when new fields are added in the
base table and those fields are not required in the program.

Disadvantages of View
1. When a query is executed on view, then it executes twice.
First time to execute view and second time to execute query on view.
2. When a table is dropped, then view becomes inactive
3. Some situations unnecessary data is retrieved from base table and a less data is
required from this view then it degrades the performance
4. DML(Insert, Update, delete) is not allowed when it is declared on multiple tables
with join

Non updatable views/Read only views


1. DISTINCT is used in the view definition
2. Aggregate function is used on columns
3. Join used on view definition
4. Group by and having clause is used
5. View is created with sub-queries

Index Spaces:
Only one index is stored in an indexed space.
An Index space is automatically created when the corresponding index is created.
Pages in an index space are 4k bytes in size.
Index space for partitioned table space is partitioned.

Index:
An index contains values from one or more of a table’s columns and a pointer to the record in a
data which matches the index value. DB2 will find data more efficiently by scanning the index
and following the pointer than by scanning the entire tablespace.

Index consists of two parts, Record id (RID) and Indexed value.


Record ID of index has two parts. First part is to identify the page where the record lies and the
second part is the byte offset from the bottom of the page identifying the record. Index is
structured in ascending or descending sequence on one or more columns. A given value of
interest can be located quickly in the index because of their ascending or descending structure.

10
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

In the example, Index is used to find a Record (T) in Page P.


INDEX 1

RID VALUE

PAGE P

An index created on a table in a partitioned table space is a partitioned index and is divided into
multiple index spaces.
Indexes are of two types, unique and non unique indexes. A non unique index can reference
duplicate values, a unique index will not. You can create an index any time after you create the
table. But creating an index before loading the data provides significant performance advantages.
Indexes can be clustered or non clustered. A clustering index is one in which the records are
physically stored in data pages in the sequential order of their index values. The index is used to
control physical placement of the indexed records. Newly inserted records are physically stored
such that the physical sequence of those records in storage closely approximates the logical
sequence as defined by the index. In a non clustered index the records will not be in the order of
index values.
A table can have any number of indexes but it can have only one clustered index.
Clustering is extremely important for optimization purpose. The optimizer will try to choose an
access path based on the clustering index .

Table Data and Index Data


EMP Table Index on Emp_num Index on Salary
E001 20000.00 E001 Row1 10000.00 Row7
E002 30000.00 E002 Row2 15000.00 Row6
E004 20000.00 E003 Row4 15000.00 Row8
E003 30000.00 E004 Row3 20000.00 Row1
E005 20000.00 E005 Row5 20000.00 Row3
E008 15000.00 E006 Row8 20000.00 Row5
E007 10000.00 E007 Row7 30000.00 Row2
E006 15000.00 E008 Row6 30000.00 Row4
Records in the table are not in the sorted order on any field.
Records in the index are in the ascending order on the index field.
Select on the table takes index scan when there is index created on predicate, otherwise it takes
table scan. Table scan is much slower than index scan.

EMP Table Clustering Index on emp_num Index on salary


E001 20000.00 E001 Row1 10000.00 Row7
E002 30000.00 E002 Row2 15000.00 Row8
E003 30000.00 E003 Row3 15000.00 Row8
E004 20000.00 E004 Row4 20000.00 Row1
E005 20000.00 E005 Row5 20000.00 Row4
E006 15000.00 E006 Row6 20000.00 Row5

11
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

E007 10000.00 E007 Row7 30000.00 Row2


E008 15000.00 E008 Row8 30000.00 Row3

Records in the table will be stored in the same order of clustering index. Only one clustering
index can be created on table.

Aliases:
An Alias is an alternative name for a Table or View. It is a qualified name that can be used by any
Authorization id.
An Alias can be defined for a table or view that was created by some other user and for which
you would otherwise have to use a fully qualified name.
Aliases were designed for a distributed environment to avoid having to reference the location
qualifier of table or view.
Alias is not private to the creator.
An alias can be defined on an undefined name. That is the object on which the alias is created
need not be present at the creation time.

Synonyms:
Synonyms are useful for creating more meaningful name for a person using a Table or View.
A Synonym is an unqualified name that can only be used by the Authorization id that created it.
A Synonym is private to the user who creates it.
Synonym cannot refer to remote Table in a distributed data environment.
A Synonym can only be defined on the name of an existing Table or View.

DB2 Catalog:
The CATALOG in DB2 is a system database that contains information concerning various
objects that are of interest to DB2 itself. Examples of such objects are tables, views, indexes,
databases, plans, packages, access privileges, and so on. These information is essential, if the
system is to able to do it’s job properly.
CATALOG itself contains TABLES and you can see the contents of catalog tables using normal
query language ( SQL ). When you create, drop or alter any structure, DB2 updates or deletes
rows of the catalog that describe the structure.

Example of Catalog Tables


SYSIBM.SYSTABLES: It contains information of a table. When a new Table is created db2
inserts one row into this catalog Table.
SYSIBM.SYSCOLUMNS: It contains information about the columns in a table. This table
contains one row for every column of each row in a Table.
SYSIBM.SYSTABLESPACE: It contains information of the table space created. The table
contains one row for each tablespace.
SYSIBM.SYSTABAUTH: It contains information of the table names and Authorization id’s
which have privileges on that table.

DB2 Directory:
It contains information required to start db2 and db2 uses the directory during normal operation.
It consists of a set of db2 Tables stored in 5 table spaces in system database DSNDB01.
1. SKELETON CURSOR TABLESPACE (SCT02) contains Plans.
2. SKELETON PACKAGE TABLE (SPT01) contains Packages.
3. LOG RANGE TABLE SPACE (SYSLGRNX) contains the RBA (Relative byte address ) and
the log dataset.
4. SYSTEM UTILITIES TABLE SPACE (SYSUTILX) contains the information about

12
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Running UTILITIES.

5.THE DATABASE DESCRIPTOR TABLE SPACE (DBD01) contains interval control


Blocks that describe the databases existing within db2.
6. Cannot Access DIRECTORY Using SQL.

Active and Archive logs:


Db2 records all data changes and significant events in a log as they occur.
Db2 writes each log record to a DASD Dataset called the Active Log.
When the Active log is full, Db2 copies the contents of the Active Log to a DASD
Called the Archive Log. The Archive Log can consist of up to 1000 datasets each of which is a
sequential dataset. In the case of failure Db2 uses Logs to recover data.

Buffer Pools:
Buffer pools, also known as virtual buffer pools, are areas of virtual storage used temporarily to
store pages of table spaces or indexes. When an application program needs to access a row of a
table, DB2 retrieves the page containing that row and places the page in a buffer. If the row is
changed, the buffer must be written back to the table space. If the needed data is already in a
buffer, the application program will not have to wait for it to be retrieved from DASD. The result
is faster performance.

DB2 can provide 2 types of buffer pools, 4K and 32K buffer pools. There are fifty 4K buffer
pools named BP0, BP1, P49 and ten 32K buffer pools named BP32K, BP32K1, BP32K9.

DB2 DATA TYPES

Data type depends on the nature of the data itself and will always be one of two types NUMERIC
or CHARACTER .

Types of CHARACTER column


CHAR – Allows any values to be entered in the column. All entries are the same length
VARCHAR – Allows any values to be entered in the column. All entries are the varying length.

Types of NUMERIC columns


INTEGER - For very large integers up to 2,147,483,647
SMALLINT - For small integer up to 9999

DECIMAL - For numbers with a fixed number of decimal places after the decimal point. The
number can have a total of 15 digits
FLOAT -For very large numbers with an undetermined number of decimal places after the
decimal point .

Types of DATE/TIME columns


DATE - Dates are stored in YYYYMMDD format
TIME - Times are stored on a 24-hour clock in HHMMSS format
TIMESTAMP – TIMESTAMP columns contain both date and time information, with the time
value accurate to the millisecond.

13
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Db2 Data types and equivalent host variables

DB2 Column Bytes Cobol PIC clause Bytes


SMALLINT 2 PIC S9(04)COMP 2

INTEGER 4 PIC S9(09)COMP 4

DECIMAL(P,Q) INT(P/2) PIC S9(P-Q)V9(Q) INT(P/2 +1)


(P Should be less than 32)

DATE 4 PIC X(10) 8

TIME 3 PIC X(08) 6

TIMESTAMP 10 PIC X(26) 26

CHAR(N) (N =1 to 254) N PIC X(N) N

VARCHAR(N) (N = 0-4046) N 01 COL-NAME. N+2


49 COL-NAME-LEN PIC S9(4)COMP.
49 COL-NAME-TEXT PIC X(N).

14
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

STRUCTURED QUERY LANGUAGE (SQL)

A powerful database management language that performs the function of data manipulation, data
definition and data control and a non-procedural language.

SQL - Types (based on the functionality)

Data Definition Language (DDL)


- Create, Alter and Drop

Data Manipulation Language (DML)


- Select, Insert, Update and Delete

Data Control Language (DCL)


- Grant and Revoke

Data Definition Language (DDL)


DDL statements are used to create and maintain DB2 objects like storage groups, databases,
table spaces, tables, indexes, synonyms, aliases and views.
CREATE  Defines a new db2 object.
ALTER  Changes the characteristics of a db2 object.
DROP  Removes an existing db2 object.
These can be executed interactively or embedded in an application program.

DDL - CREATE STOGROUP


Creates a storage group and specifies a list of volumes that db2 can use in the order specified in
the statement.
Syntax:
CREATE STOGROUP stogroup-name
VOLUMES (vol1, vol2, ...)
VCAT catalog-name
[PASSWORD password]

DDL - ALTER STOGROUP


The ALTER STOGROUP statement can be used to add or remove DASD volumes associated
with the storage group. In the example adds the volumes DBPK03 and removes DBPK01 from
the storage group description.
Syntax:
ALTER STOGROUP stogroup-name
ADD VOLUMES (vol4, vol5, ...)
REMOVE VOLUMES (vol1, vol2, ...)
[PASSWORD password]
Example:
ALTER STOGROUP TRG1T01
ADD VOLUMES (DBPK03)
REMOVE VOLUMES (DBPK01)

DDL - CREATE DATABASE


The create database statement defines a db2 database to the db2 subsystem. The name must not
start with DSNDB and must not identify an existing database. In this statement you can specify
the name of buffer pool and storage group for table spaces and indexes with the database.

15
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

If buffer pool is not specified in the create database statement then default buffer pool used is
BP0.If storage group is not specified in the create database statement then default storage group
used is SYSDEFLT.
Syntax:
CREATE DATABASE database-name
[STOGROUP stogroup-name]
[BUFFERPOOL bufferpool-name]

DDL - CREATE TABLESPACE


Syntax:
CREATE TABLESPACE tablespace-name
[IN database-name]
[USING {VCAT VSAM-CATALOG-NAME/STOGROUP stogroup-name}]
[PRIQTY qty]
[SECQTY qty]
[ERASE YES/NO]
[LOCKSIZE ANY/PAGE/TABLESPACE/TABLE]
[BUFFERPOOL BP0/BP1/BP2/BP32K]
[CLOSE YES/NO DSETPASS password]
[FREEPAGE <amount>]
[PCTFREE <amount>]
database-name : The database in which the tablespace should be created. The default is
DSNDB04.
USING clause: The method of storage allocation for the tablespace is defined using the USING
parameter. In this clause, the STOGROUP name combined with the a primary (PRIQTY) and
secondary quantity(SECQTY) for space allocation can be specified or a VCAT identifier for user-
defined VSAM data sets. In future, we assume that the STOGROUP is specified.
primary allocation (PRIQTY): It is the amount of physical storage allocated when the
tablespace is created. The amount of storage space specified in qty must be available on the first
volume. As the amount of data in the tablespace grows, secondary allocations of storage
(SECQTY) are taken.
• If the PRIQTY is not specified, it is 3
• If the PRIQTY is specified, and if the page size of the table is
- 4K bytes, then the number is qty/4 rounded upto the next highest integer, but not less than 3.
- 32K bytes, then the number is qty/32 rounded upto the next highest number, but not less
than 3.
Similar rules are applicable for SECQTY also.
ERASE option: It specifies whether the physical DASD where the tablespace data set resides
should be written over with binary zeroes when the tablespace is dropped. The default is ERASE
NO.
Locksize parameter: It specifies the type of locking DB2 performs for the given tablespace.
PAGE - Page level locking
TABLE- Table-level locking (for segmented tablespaces only)
TABLESPACE - Tablespace-level locking
ANY - Lets DB2 decide, starting with PAGE (default value)
In general, it is best to let DB2 handle the level of locking required i.e.. ANY option. Locking
begins with PAGE locks and escalates to TABLE or TABLESPACE locks if DB2 determines
that the number of page locks acquired for a tablespace exceeds the maximum number of locks
allowed for a tablespace (an installation parameter).
Bufferpool option:
The four bufferpool options for DB2 objects consist of three 4K bufferpools - BP0, BP1, BP2 -
and one 32K bufferpool - BP32K. The default value is the bufferpool name for the database.

16
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

CLOSE option: It tells whether to close the data sets supporting the table space when there are
no current users of the table space. The dafault value is CLOSE YES.
FREEPAGE parameter : It specifies how often to leave a page of free space when the
tablespace or partition is loaded or reorganized. It can take values from 0 to 255. If the value is 0,
no free pages are left as free space. Otherwise, one free page is left after every amount pages.
PCTFREE parameter: It tells what percentage of each page to leave as free space when the
table is loaded or reorganized. amount may vary from 0 to 99. The first record in each page is
loaded without restriction. The default value is PCTFREE 5.
Example:
CREATE TABLESPACE
IN DSN8D2AP
USING STOGROUP DSNS6200
PRIQTY 12
SECQTY 12
ERASE NO
LOCKSIZE ANY
CLOSE YES
BUFFERPOOL BP0.

DDL - CREATE TABLE


Syntax1:
CREATE TABLE tablename
( column-definition [, column-definition] ...
[, primary-key-definition]
[, foreign-key-definition
[, foreign-key-definition] ...]
[other-parameters] )
[ IN databasename.tablespacename /
IN DATABASE databasename]
Create table statement creates a table in a table space. Table name is unique for a user. If USERA
Creates TABLEA then fully qualified name will be USERA.TABLEA .
USERA can simply use the name TABLEA but other users must specify fully qualified name.
if the tablename is unqualified, the SQL ID is the owner of the table.

column-definition:
The columns of the table are identified using this parameter. Column name column type [NOT
NULL / NULL / NOT NULL WITH DEFAULT] This defines the name, column type associated
with each of the columns of the table. The column name can be a maximum of 18 characters
starting with an alphabet.
The column type can be any of the DB2 data types. The column can be of one of the following
types.
NOT NULL - cannot contain null values
NULL - can have null values
NOT NULL WITH DEFAULT - prevents a column from containing null values, and allows a
default value other than the null value.

Data Type Default Value


Numeric 0
Fixed-length string blanks
Varying-length string a string of length 0
Date current date
Time current time

17
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Timestamp current timestamp

When NOT NULL or NOT NULL WITH DEFAULT is not specified, then the column is
nullable.

primary-key-definition:
Primary key of a table is the unique identifier for that table. A Table cannot have more than one
primary key, and the columns of a primary key cannot contain null values. When a primary key is
defined on a table, a unique index must be created on that primary key.
This parameter defines the columns that form the primary key.
PRIMARY KEY (colname1, colname2, ...)

foreign-key-definition:
This parameter defines the foreign key(s) associated with the table.
FOREIGN KEY [constraint-name]
(colname1 [, colname2] ...)
REFERENCES base-table
[ON DELETE RESTRICT / CASCADE /
SET NULL]
Each specification of the FOREIGN KEY defines a referential constraint with the specified name.
A name is generated if the constraint-name is not specified. The foreign key of the referential
constraint is composed of the specified columns. Each name in the column list must identify a
column of the table. The base-table identified in the after the REFERENCES must identify a table
in the catalog.
The delete rule of the relationship is determine by the ON DELETE clause. The default value is
ON DELETE RESTRICT. This rule is explicitly specified for each foreign key in a table. The
DELETE rule states the requirements to be met when ....
“... a row in a parent table is deleted. Each foreign key is associated with its own DELETE rule.
All applicable DELETE rules are used to determine whether or not a delete is done.”

RESTRICT option A row of a parent table cannot be deleted if rows exist in the dependent
table(s) with foreign key values equal to the primary key value of this row.

CASCADE option If a row of a parent table is deleted, then: all rows in the dependent table(s)
with foreign key values equal to the primary key value of this row will also be deleted. The delete
will also impact the dependents of the dependent table(s).

SET NULL option If a row of a parent table is deleted then all rows in the dependent table with a
foreign key value equal to the primary key value of this row will have its foreign key value
changed to NULL.

IN clause:
This specifies the database and tablespace in which the table is created. If the IN DATABASE
clause is used then a tablespace is implicity created with name derived from the tablename.

Example:
CREATE TABLE EMPLOYEE(
EMPNO CHAR(6) NOT NULL PRIMARY KEY,
FNAME CHAR(10),
LNAME CHAR(10) NOT NULL,
DEPTNO CHAR(03),
SALARY DECIMAL(9,2) NOT NULL)

18
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

IN DB-NAME.TS-NAME;

Syntax 2:
CREATE TABLE tablename
LIKE existing-tablename

This format allows the user to create a table tablename with the same column description as
some existing table existing-tablename. The table tablename does not inherit any primary or
foreign key definitions from existing-tablename.
Example:
CREATE TABLE EMPLOYEE.TEMP LIKE EMPLOYEE IN DB-NAME.TS-NAME;

DDL – CREATE VIEW


Syntax:
CREATE VIEW view-name
[(column-name, ...)]
AS SELECT column-name, column-name, …….
FROM table-name
[WHERE condition]
[WITH CHECK OPTION]
The CREATE VIEW creates a view on one or more tables or views.
If the view name in unqualified then the Authorization id is the implicit qualifier.
The column-name is a list of columns in the view. If the column names are not specified, then the
view inherits the names of the columns used in the subselect. The view consists of rows that
result from the execution of the subselect.

Example:
CREATE VIEW EMP_VIEW
AS SELECT EMPNO,NAME,DEPT,JOB FROM EMPLOYEE.

DDL – CREATE INDEX


Syntax:
CREATE [UNIQUE] INDEX indexname
ON tablename (colname [ASC/DESC], ...)

UNIQUE: Prevents the table from containing two or more rows with the same value of the index
key. There can be more than one UNIQUE INDEX for a table. Uniqueness is checked during
Update, Insert or LOAD of insert key. The constraint is also checked during the CREATE
INDEX statement. If the table contains rows with duplicate values, then the index is not created.
ASC/DESC : The index entries are put in ascending order by the column with ASC and in
descending order with DESC. The default value is ASC.
Creating unique index on a null column is possible if there is only one null is available in that
column.
Example:
CREATE UNIQUE INDEX EMPI ON EMPLOYEE (EMPNO);
(or)
CREATE TYPE 2 UNIQUE INDEX EMPI ON EMPLOYEE (EMPNO);

DDL – CREATE SYNONYM


Syntax:
CREATE SYNONYM synonym-name
FOR userid.table-name/userid.view-name
The CREATE SYNONYM defines a synonym for a table or view.

19
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

FOR introduces the name of table or view to which the synonym will apply. The name must be
qualified.

DDL – CREATE ALIAS


Syntax:
CREATE ALIAS alias-name
FOR userid.table-name/userid.view-name
The CREATE ALIAS defines a alias for a table or view.

DDL - ALTER Statement


Syntax
ALTER TABLE tablename
ADD column-definition
ADD PRIMARY-KEY column-name
ADD FOREIGN KEY [constraint-name] (column-name[,column-name….])
REFERENCES base-table
[ON DELETE RESTRICT / CASCADE / SET NULL]

DROP PRIMARY KEY


DROP FOREIGN KEY constraint-name

Alter is a DDL statement and it is used to the change the table definition on the below reasons.
1. To add/drop column to the table
2. To change an existing column definition to increase length of the field.
3. To add/drop constraints

Different types in alter statement


ALTER TABLE tab1 DROP COLUMN c1;
ALTER TABLE tab1 DROP COLUMN c1 DROP COLUMN c2 DROP COLUMN c3;
ALTER TABLE tab1 ADD COLUMN c1 INT NOT NULL;
ALTER TABLE tab1 ADD COLUMN c1 INT NOT NULL ADD COLUMN c2 CHAR(40);
ALTER TABLE tab1 ALTER COLUMN c1 SET DATA TYPE INT;
ALTER TABLE tab1 ALTER COLUMN c1 SET DATA TYPE CHAR(20);
ALTER TABLE tab1 ALTER COLUMN c1 SET NOT NULL;
ALTER TABLE tab_emp ADD CONSTRAINT fk_dept FOREIGN KEY(dept_no)
REFERENCES tab_dept(deptno) ON DELETE SET NULL;

ALTER TABLE EMP ADD CONSTRAINT unique_passport UNIQUE(passport_num));


ALTER TABLE EMP ADD CONSTRAINT Manager_age CHECK (JOB = 'Mgr' and AGE >= 40)

REORG-recommended ALTER
Reorg is recommended when table row format is altered otherwise table turned into reorg
pending status. In this case all operations on the table cannot be executed.

Ex of reorg recommended operations


ADD column
DROP column
Alter Column set data type..
Ex of reorg not recommended operations
Alter column set not null
ADD Constraint

Authorization required for ALTER


The privileges held by the authorization ID of the statement must include at least one of the
following:

20
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

• ALTER privilege on the table to be altered


• CONTROL privilege on the table to be altered

• ALTERIN privilege on the schema of the table


• SYSADM or DBADM authority
• REFERENCES privilege on the table to drop or create foreign key

How to do reorg on the table/index


REORG TABLE table_owner.table_name
REORG TABLE table_owner.table_name
REORG INDEXE Index1;
REORG INDEXES ALL FOR TABLE table_owner.table_name

Runstats after Reorg


Execute runstats after Reorg then it collects latest statistics of the table.
RUNSTATS ON TABLE table_owner.table_name FOR INDEXES ALL

DDL - DROP Statement


Syntax:
DROP OBJECT-TYPE OBJECTNAME
The DROP statement deletes an object. Any objects that are directly or indirectly dependent on
that object are also deleted. object-type can be TABLE, VIEW, INDEX, SYNONYM,
STOGROUP, DATABASE, TABLESPACE.

Example:
DROP DATABASE TRG1T01
DROP TABLE SUPPLIER
DROP INDEX XS

Constraints

Constraints are used to maintain data integrity. These constraints imposes rules on fields.
Different types of constraints.
1. Primary Key
2. Foreign key
3. Unique
4. Check

CREATE TABLE EMP_TBL


(ID SMALLINT NOT NULL PRIMARY KEY,
COUNTRY_CODE CHAR(3) NOT NULL,
FIRST_NAME CHAR(20),
LAST_NAME CHAR(20).
DEPTNO SMALLINT CHECK (DEPT BETWEEN 10 AND 100),
JOB_CODE CHAR(5) CHECK (JOB IN ('Sales', 'Mgr', 'Clerk')),
HIREDATE DATE,
PASSPORT_NO CHAR(10) UNIQUE,
AGE SMALLINT CHECK (AGE >=21),
SALARY DECIMAL(7,2),
COMM DECIMAL(7,2),

FOREIGN KEY(DEPTNO) REFERNCES DEPT_TBL(DEPTNO)


ON DELETE CASCADE/SET NULL/RESTRICT,

CONSTRAINT unique_name UNIQUE(FIRST_NAME, LAST_NAME),


CONSTRAINT Manager_age CHECK (JOB = 'Mgr' and AGE >= 40))

21
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

IN DBNAME.TSNAME;

Primary key constraint


• Primary key should be unique and only primary key can be coded on a table.
As shown in the table declaration, if a primary key is created on single column then it can
be coded at column level. If the primary key has to be created on multiple fields then code
after the column definitions but not on column level.
Ex: Create a primary key with COUNTRY_CODE first and ID next. Now the combination of
COUNTRY_CODE and ID is unique. Then code it as shown below.
PRIMARY KEY(COUNTRY_CODE, ID)

Foreign Key constraint


• Foreign key is used to create a relation between child table and parent table.
• A field used in the child table for the relation is called foreign key and field related in the parent
parent table is called Primary key.
• Parent table should be created prior to create a foreign key in the child table.
• Foreign key in the child table need not be unique.
• Foreign key can be created with single or multiple fields.
• Foreign key can be coded with delete contraints. It says about what is the restriction
rule to delete parent record when that has a reference record in the child table.
Ex: DEPTNO in EMP_TBL is created as foreign key that relates DEPT_NO in the parent table.
ON DELETE CASCADE : When department is deleted from parent table then all employees
on child table for that department will be deleted automatically.
ON DELETE SET NULL : When department is deleted from parent table then all employees
on child table for that department will be set with NULL on
DEPNO field.
ON DELETE RESTRICT : When trying to delete a department from parent table, if any
employee is referenced to that department in the child table then
parent record cannot be deleted.
Make sure there are no child records on that parent record and
then delete parent record.

Unique constraint
• It will enforce unique key on a single field or combination of multiple fields
• If it is given on a single field then it can be coded in the column definition otherwise it should
be declared at the end of the column definition in the table declaration.
Ex1: PASSPORT_NO should be unique
Ex2: Combination of FIRST_NAME and LAST_NAME should be unique

CHECK Constraint
• It will enforce the list of values or range of values for the given column or columns.
• If a constraint on the single field then it can be coded on the field definition otherwise it should
be at the end of the column definition in the table declaration.
Ex1: DEPTNO can be inserted or updated with values between 10 and 100.
Ex2: JOB can be updated only with list of values 'Sales' or 'Clerk' or 'Mgr'
Ex3: Check constraint on multiple fields
If the value in the job is 'Mgr' then age should be >= 40

22
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

ADD/DROP constraints
All the above 4 constraints can be added/dropped with alter statement as shown below.
Examples:
1. ALTER TABLE EMP_TBL ADD CONSTRAINT Clrek_sal
CHECK (JOB = 'Clerk' and SALARY < 50000.00);
2. ALTER TABLE EMP_TBL DROP CONSTRAINT Manager_age;
3. ALTER TABLE EMP_TBL ADD CONSTRAINT fk_Jobs
FOREIGN KEY(JOB_CODE)
REFERENCES JOBS_TBL(JOB_CODE) ON DELETE SET NULL;

CREATION OF EMPLOYEE TABLE

CREATE TABLE EMPLOYEE(


EMPNO CHAR(6) NOT NULL PRIMARY KEY,
FNAME CHAR(10),
LNAME CHAR(10) NOT NULL,
DEPTNO CHAR(03),
WPHONE CHAR(08) NOT NULL,
STARTDT DATE,
SEX CHAR(01) NOT NULL,
SALARY DECIMAL(9,2) NOT NULL)
IN DB-NAME.TS-NAME;

CREATE TYPE 2 UNIQUE INDEX EMPLOYEEI ON EMPLOYEE (EMPNO);

INSERT INTO EMPLOYEE VALUES


('307117','MARY ','JOHNSON ','100','290-4788','1973-05-16','F',48000.00);
INSERT INTO EMPLOYEE VALUES
('604985','JASON ','JONES ','500','290-4128','1988-04-09','M',18000.00);
INSERT INTO EMPLOYEE VALUES
('911723','SHARON ','DYLER ','300','290-4366','1979-11-21','F',30000.00);
INSERT INTO EMPLOYEE VALUES
('827611','JOHN ','LEBLANC','100','290-4875','1984-01-15','M',42000.00);
INSERT INTO EMPLOYEE VALUES
('642655','FRANK ','RYDZIK ','300','290-4789','1986-09-10','M',28000.00);
INSERT INTO EMPLOYEE VALUES
('737466','GAIL ','BAKER ','100','290-4112','2005-05-17','F',38000.00);
INSERT INTO EMPLOYEE VALUES
('215012','GARY ','SHELDON','200','290-4631','1987-02-01','M',31000.00);
INSERT INTO EMPLOYEE VALUES
('871330','KATHY ','ZWIRNER','500','290-4267','1983-08-15','F',26000.00);
INSERT INTO EMPLOYEE VALUES
('711674','FRED ','MAYR ','100','290-4211','1987-12-01','M',33000.00);

SELECT * FROM EMPLOYEE;

+------------------------------------------------------------------+
¦EMPNO ¦ FNAME¦ LNAME ¦DEPTNO¦ WPHONE ¦ STARTDT¦SEX¦ SALARY ¦
+------+--------+---------+------+--------+-----------+---+--------¦
¦307117¦MARY ¦JOHNSON ¦ 100 ¦290-4788¦ 1973-05-16¦ F ¦48000.00¦
¦604985¦JASON ¦JONES ¦ 500 ¦290-4128¦ 1988-04-09¦ M ¦18000.00¦
¦911723¦SHARON ¦DYLER ¦ 300 ¦290-4366¦ 1979-11-21¦ F ¦30000.00¦
¦827611¦JOHN ¦LEBLANC ¦ 100 ¦290-4875¦ 1984-01-15¦ M ¦42000.00¦
¦642655¦FRANK ¦RYDZIK ¦ 300 ¦290-4789¦ 1986-09-10¦ M ¦28000.00¦
¦737466¦GAIL ¦BAKER ¦ 100 ¦290-4112¦ 2005-05-17¦ F ¦38000.00¦
¦215012¦GARY ¦SHELDON ¦ 200 ¦290-4631¦ 1987-02-01¦ M ¦31000.00¦
¦871330¦KATHY ¦ZWIRNER ¦ 500 ¦290-4267¦ 1983-08-15¦ F ¦26000.00¦
¦711674¦FRED ¦MAYR ¦ 100 ¦290-4211¦ 1987-12-01¦ M ¦33000.00¦

23
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

+------------------------------------------------------------------+

CREATION OF DEPARTMENT TABLE

CREATE TABLE DEPARTMENT(


DEPTNO CHAR(3) NOT NULL PRIMARY KEY,
DEPTNAME CHAR(15),
MANAGER CHAR(6) NOT NULL)
IN DB-NAME.TS-NAME;

CREATE TYPE 2 UNIQUE INDEX DEPTI ON DEPARTMENT (DEPTNO);

INSERT INTO DEPARTMENT VALUES ('100','PRODUCTION ','737466');


INSERT INTO DEPARTMENT VALUES ('200','ACCOUNTING ','865403');
INSERT INTO DEPARTMENT VALUES ('300','PERSONNEL ','491640');
INSERT INTO DEPARTMENT VALUES ('400','ENGINEERING','604985');

SELECT * FROM DEPARTMENT;

DEPARTMENT TABLE
+-------------------------------+
¦DEPTNO¦ DEPTNAME ¦ MANAGER¦
+------+---------------+--------¦
¦ 100 ¦ PRODUCTION ¦ 737466 ¦
¦ 200 ¦ ACCOUNTING ¦ 865403 ¦
¦ 300 ¦ PERSONNEL ¦ 491640 ¦
¦ 400 ¦ ENGINEERING ¦ 604985 ¦
+-------------------------------+

DML(Data Manipulation Language)


DML statements access and modify data available in tables. SELECT and UPDATE operate on
specified columns within the rows, whereas DELETE and INSERT operate on complete rows.

SELECT  Retrieves data.


UPDATE Changes existing values.
DELETE  Removes rows from the table.
INSERT  Adds rows to the table.

The INSERT statement


It adds rows to a table.

INSERT format1:
It assigns values to columns in the order the columns appear in the table.

SYNTAX: INSERT INTO table-name


VALUE (value1, value2, ...)

EX: INSERT INTO EMPLOYEE


VALUES (283721, 'ANNE', 'PATON', 400, '290-4871', '120588', 'F', 37000.00)

EX: Write a command to add a row to the DEPARTMENT table to include the
LEGAL department, number 400.The manager's employee number is 283721.
INSERT INTO DEPARTMENT
VALUES (400, 'LEGAL', 283721);

24
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

INSERT format2:
It has entries in the column list which correspond to entries in the value list.

SYNTAX:
INSERT INTO table-name (column-1, column-2, ...)
VALUE (value1, value2, ...)

EX:
INSERT INTO DEPARTMENT (DEPTNAME, DEPTNO, MANAGER)
VALUES ('LEGAL', 400, 283721);

Multiple rows can be added to a table by copying rows from one table into another. This is
accomplished by using a query to define the set of rows to be inserted into the table.

SYNTAX:
INSERT INTO target-table(column, ...)
SELECT column, ...
FROM source table(s)
WHERE search conditions

Ex: To create a new table called MANAGER which consists of information on employees who
are managers. We could insert information into the table using a query.

INSERT
INTO MANAGER(DEPTNAME,DEPTNO,EMPNO,FNAME,LNAME,WPHONE)
SELECT DEPTNAME,DEPTNO,EMPNO,FNAME,LNAME,WPHONE
FROM DEPARTMENT,EMPLOYEE
WHERE EMPLOYEE.EMPNO = DEPARTMENT.MANAGER

MANAGER
+-------------------------------------------------+
¦ DEPTNAME ¦DEPTNO¦ EMPNO¦FNAME ¦ LNAME ¦ WPHONE ¦
+-----------+------+------+------+-------+--------¦
¦PRODUCTION ¦ 100 ¦737466¦GAIL ¦BAKER ¦290-4112¦
¦ACCOUNTING ¦ 200 ¦865403¦ALBERT¦CHILDS ¦290-4631¦
¦PERSONNEL ¦ 300 ¦911723¦SHARON¦DYLER ¦290-4366¦
¦LEGAL ¦ 400 ¦283721¦ANNE ¦PATON ¦290-4871¦
¦ENGINEERING¦ 500 ¦604985¦JASON ¦JONES ¦290-4128¦
+-------------------------------------------------+

SELECT Statement and its varieties


SELECT statement used to retrieve all or specified columns from a table.

SELECT * FROM EMPLOYEE;  To retrieve all columns from the table


SELECT DEPTNO FROM EMPLOYEE; gives the following table:
+------+
¦DEPTNO¦ +-> Note that duplicate rows
+------¦ ¦ appear in the result
¦ 100 ¦ ------+ ¦ table.
¦ 500 ¦ ¦ ¦
¦ 300 ¦ +----------+ SQL allows us to eliminate
¦ 100 ¦ ------¦ duplicate rows from a table.
¦ 300 ¦ ¦
¦ 100 ¦ ------¦
¦ 200 ¦ ¦
¦ 500 ¦ ¦

25
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

¦ 100 ¦ ------+
+------+

SELECT DISTINCT DEPTNO FROM EMPLOYEE;


+------+ We can avoid these duplications
¦DEPTNO¦ by using the DISTINCT keyword.
+------¦
¦ 100 ¦
¦ 200 ¦ <------------------ Now there is only one entry for
¦ 300 ¦ each DEPTNO.
¦ 500 ¦
+------+
SQL provides four arithmetic symbols that can be used in an expression. They are:
+ addition
- subtraction
* multiplication
/ division

SELECT LNAME, SALARY FROM EMPLOYEE;

+------------------------+
¦ LNAME ¦ SALARY ¦
+---------------+--------¦
¦JOHNSON ¦48000.00¦
¦JONES ¦18000.00¦
¦DYLER ¦30000.00¦
¦LEBLANC ¦42000.00¦
¦RYDZIK ¦28000.00¦
¦BAKER ¦38000.00¦
¦SHELDON ¦31000.00¦
¦ZWIRNER ¦26000.00¦
¦MAYR ¦33000.00¦
+------------------------+

The SALARY column lists the annual income for each employee. If we want to know the
monthly income we can use the calculation feature to divide each salary by 12.

SELECT LNAME, SALARY/12 FROM EMP


^
|
+-------------------------+
¦ LNAME ¦SALARY/12¦
+---------------+---------¦
¦JOHNSON ¦ 4000.00 ¦
¦JONES ¦ 1500.00 ¦
¦DYLER ¦ 2500.00 ¦
¦LEBLANC ¦ 3500.00 ¦
¦RYDZIK ¦ 2333.33 ¦
¦BAKER ¦ 3166.67 ¦
¦SHELDON ¦ 2583.33 ¦
¦ZWIRNER ¦ 2166.67 ¦
¦MAYR ¦ 2750.00 ¦
+-------------------------+

The arithmetic expression SALARY/12 is displayed as a new column in the table.


Ex: Write a query that would display the employee number (EMPNO) and SALARY if all
employees were given a 10 % salary increase.

SELECT EMPNO,SALARY * 1.1 FROM EMPLOYEE;

26
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

WHERE CLAUSE

The WHERE clause works as a filter to choose only those rows in a table that satisfy the search
condition.

SELECT column name(s) FROM tablename WHERE .........

For example: If we wanted to list only the employees that are in department 300, from the
employee table
SELECT *
FROM EMPLOYEE WHERE DEPTNO = 300;

+------------------------------------------------------------------------+
¦EMPNO ¦ FNAME ¦ LNAME ¦DEPTNO¦ WPHONE ¦STARTDT¦SEX¦ SALARY ¦
+------+------------+---------------+------+--------+-------+---+--------¦
¦911723¦SHARON ¦DYLER ¦ 300 ¦290-4366¦112179 ¦ F ¦30000.00¦
¦642655¦FRANK ¦RYDZIK ¦ 300 ¦290-4789¦091086 ¦ M ¦28000.00¦
+------------------------------------------------------------------------+

Ex: 1. SELECT EMPNO, LNAME, SEX, SALARY


FROM EMPLOYEE
WHERE SEX = 'F';

Note: when a character string is used in a search condition it is enclosed in single quotes.
+-----------------------------------+
¦EMPNO ¦ LNAME ¦SEX¦ SALARY ¦
+------+---------------+---+--------¦ +----- Only those rows where
¦307117¦JOHNSON ¦ F ¦48000.00¦ ¦ SEX = 'F' are included
¦911723¦DYLER ¦ F ¦30000.00¦ ¦ in the table
¦737466¦BAKER ¦ F ¦38000.00¦ ¦
¦871330¦ZWIRNER ¦ F ¦26000.00¦ ¦
+-----------------------------------+ ¦
| ¦
|--------------+
Ex: 2. Write a query to retrieve all the columns from the EMPLOYEE table for those whose last
name (LNAME) is JONES.
SELECT * FROM EMPLOYEE WHERE LNAME='JONES';

The comparison operators available to use with the WHERE clause as a search condition is:
= equal to
<> or ¬= not equal to
> greater than
>= greater than or equal to
< less than
<= less than or equal to
Sometimes you will need to link more than one search condition in a WHERE command.
Multiple search conditions are linked by:
AND - meaning All conditions MUST be met
OR - meaning AT LEAST ONE condition must be met

SELECT EMPNO, LNAME, DEPTNO, SALARY


FROM EMPLOYEE
WHERE DEPTNO = 200
OR DEPTNO = 300

27
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

OR DEPTNO = 500;

List the rows in a table that meet one of several criteria using the OR operator. To achieve the
same result by using the set comparison operator IN.

SELECT EMPNO, LNAME, DEPTNO, SALARY


FROM EMPLOYEE
WHERE DEPTNO IN (200,300,500)

+-------------------------------+
¦EMPNO ¦ LNAME ¦DEPTNO¦ SALARY ¦
+------+--------+------+--------¦ Note that only the department
¦604985¦JONES ¦ 500 ¦18000.00¦ numbers in the list were
¦911723¦DYLER ¦ 300 ¦30000.00¦ selected.
¦642655¦RYDZIK ¦ 300 ¦28000.00¦
¦215012¦SHELDON ¦ 200 ¦31000.00¦
¦871330¦ZWIRNER ¦ 500 ¦26000.00¦
+-------------------------------+

SELECT EMPNO, LNAME, SALARY


FROM EMPLOYEE
WHERE SALARY >= 30000
AND SALARY <= 50000 ;

We can list the rows in a table that fall within a specified range of values by using the AND
operator.
The BETWEEN operator lets us select rows that contain values within a specified range.
BETWEEN has the same effect as using >= AND <=.

SELECT EMPNO, LNAME, SALARY


FROM EMPLOYEE
WHERE SALARY
BETWEEN 30000 AND 50000 ;

+------------------------+
¦EMPNO ¦ LNAME ¦ SALARY ¦
+------+--------+--------¦
¦307117¦JOHNSON ¦48000.00¦
¦911723¦DYLER ¦30000.00¦
¦827611¦LEBLANC ¦42000.00¦
¦737466¦BAKER ¦38000.00¦
¦215012¦SHELDON ¦31000.00¦
¦711674¦MAYR ¦33000.00¦
+------------------------+

Write a query to want all the information on the employees JONES, JOHNSON and DYLER.

SELECT * FROM EMPLOYEE


WHERE LNAME IN ('JONES', 'JOHNSON', 'DYLER');

Another form of selection criteria which is useful is to compare a column with a specific part of a
constant. The SQL operator for this is... LIKE.
The syntax for using LIKE is ...
SELECT ...
FROM ...
WHERE column name
LIKE quoted-string

28
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

A quoted-string may contain any string of characters. Special meanings are reserved for the
characters _ and %. _ (underscore) represents any single character. % represents any string of
zero or more characters.

Ex: In order to list all employees whose name begins with a 'J' from the EMPLOYEE table .
SELECT *
FROM EMPLOYEE
WHERE LNAME
LIKE 'J%' ;

+------------------------------------------------------------------------+
¦EMPNO ¦ FNAME ¦ LNAME ¦DEPTNO¦ WPHONE ¦STARTDT¦SEX¦ SALARY ¦
+------+------------+---------------+------+--------+-------+---+--------¦
¦307117¦MARY ¦JOHNSON ¦ 100 ¦290-4788¦051673 ¦ F ¦48000.00¦
¦604985¦JASON ¦JONES ¦ 500 ¦290-4128¦040988 ¦ M ¦18000.00¦
+------------------------------------------------------------------------+
?
¦
¦ Only rows were selected
+--------------- WHERE LNAME begins with
the letter 'J'.
To retrieve information on an employee but you are uncertain whether his name is SHELDON or
SHELTON
SELECT *
FROM EMPLOYEE
WHERE LNAME
LIKE 'SHEL_ON';

+------------------------------------------------------------------------+
¦EMPNO ¦ FNAME ¦ LNAME ¦DEPTNO¦ WPHONE ¦STARTDT¦SEX¦ SALARY ¦
+------+------------+---------------+------+--------+-------+---+--------¦
¦215012¦GARY ¦SHELDON ¦ 200 ¦290-4631¦020187 ¦ M ¦31000.00¦
+------------------------------------------------------------------------+
?
¦
¦ Only the row where LNAME
+---------- matched the string in the
LIKE clause was retrieved.

ORDER BY CLAUSE
The ORDER BY clause can be used to display information in either ascending (ASC) or
descending (DESC) order. The default is ASC. SQL assumes ASC if you do not specify a value.

Ex .1:
SELECT DEPTNO, EMPNO, LNAME, SALARY/12
FROM EMPLOYEE
WHERE SEX = 'F'
ORDER BY DEPTNO;

+---------------------------------+
¦DEPTNO¦EMPNO ¦ LNAME ¦SALARY/12¦
+------+------+---------+---------¦
¦ 100 ¦737466¦BAKER ¦ 3166.67¦
¦ 100 ¦307117¦JOHNSON ¦ 4000.00¦
¦ 300 ¦911723¦DYLER ¦ 2500.00¦
¦ 500 ¦871330¦ZWIRNER ¦ 2166.67¦

29
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

+---------------------------------+
NOTE: SQL assumed ascending order.

Ex .2:
If we had wanted to list the department numbers in descending order the command would be
SELECT DEPTNO, EMPNO, LNAME, SALARY/12
FROM EMPLOYEE
WHERE SEX = 'F'
ORDER BY DEPTNO DESC;

+---------------------------------+ +------------------------+
¦DEPTNO¦EMPNO ¦ LNAME ¦SALARY/12¦ ¦ Note, the department ¦
+------+------+---------+---------¦ +---- ¦ numbers are now listed ¦
¦ 500 ¦871330¦ZWIRNER ¦ 2166.67¦ ¦ ¦ in descending order ¦
¦ 300 ¦911723¦DYLER ¦ 2500.00¦ ¦ +------------------------+
¦ 100 ¦307117¦JOHNSON ¦ 4000.00¦ ¦
¦ 100 ¦737466¦BAKER ¦ 3166.67¦ ¦
+---------------------------------+ ¦
? ¦
+-----------------------------------+

Ex .3:
SELECT DEPTNO, EMPNO, LNAME, SALARY/12
FROM EMPLOYEE
WHERE SEX = 'F'
ORDER BY DEPTNO, LNAME;

Select statement will first order the rows by DEPTNO, then order them alphabetically within each
department. The columns named for ordering must be columns selected.
+---------------------------+
+---------------------------------+ ¦ Notice that DEPTNO is now ¦
¦DEPTNO¦EMPNO ¦ LNAME ¦SALARY/12¦ +----¦ ordered by department ¦
+------+------+---------+---------¦ ¦ ¦ number in ascending order.¦
¦ 100 ¦737466¦BAKER ¦ 3166.67¦ ¦ +---------------------------+
¦ 100 ¦307117¦JOHNSON ¦ 4000.00¦ ¦
¦ 300 ¦911723¦DYLER ¦ 2500.00¦ ¦ +---------------------------+
¦ 500 ¦871330¦ZWIRNER ¦ 2166.67¦ ¦ ¦ The last names are in ¦
+---------------------------------+ +----¦ alphabetical order within ¦
? ? ¦ ¦ each department. ¦
+-----------------------------------+ +---------------------------+

It is possible to use the position of the column in place of its name in an ORDER BY clause.
Whether the name or column number is used the result is the same.
+-------------+ +---------------+
¦ ? ? ¦
¦ SELECT DEPTNO, EMPNO, LNAME, SALARY/12 ¦
¦ FROM EMPLOYEE ¦
¦ WHERE SEX = 'F' ¦
¦ ORDER BY 1, 3 ¦
¦ ? ? ¦
+-----------+ +-----------------------------+

30
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Intersection of Tables
SQL allows you to select data from more than one table. In relational terms, this is called an
intersection of tables.

Ex: To want the name of the department where SHELDON works.


The first step would be to find the department number where SHELDON works from the
EMPLOYEE table.
Results of the first step is this table.
SELECT LNAME,DEPTNO +-----------------+
FROM EMPLOYEE ¦ LNAME ¦DEPTNO¦
WHERE LNAME = 'SHELDOM'; +----------+------¦
¦ SHELDON ¦ 200 ¦
+-----------------+

Next we would place this result (DEPTNO = 200) in a query to find the name of this department.
+--------------------+
SELECT DEPTNO, DEPTNAME ¦DEPTNO¦ DEPTNAME ¦
FROM DEPARTMENT +------+-------------¦
WHERE DEPTNO = 200; ¦ 200 ¦ACCOUNTING ¦
+--------------------+

Using this two-step process to find SHELDON's department name, we are unable to list the
employee name and the department name on the same result table. This problem would be worse
if we wanted to match many employee's names with their department name.

SQL provides us with a JOIN of tables feature to combine information from more than one table
into a single result table. The tables must have a common column of data. The columns need not
have the same name, but they must contain the same type of data.

The general form of a select from two tables is:

SELECT column-names
FROM table1-name, table2-name
WHERE table1-name.column-name = table2-name.column-name;

EX:
SELECT LNAME, DEPTNAME
FROM EMPLOYEE, DEPARTMENT ?---------------------+
WHERE EMPLOYEE.DEPTNO = DEPARTMENT.DEPTNO; ¦
? ? ¦
¦ ¦ Note that the tables to be joined
¦ ¦ are listed in the FROM clause.
¦ ¦
¦ ¦ WHERE specifies the join criteria,
¦ ¦ the common link between the tables.
¦ ¦ The data types in the columns from
+---------------------- the two tables must be the same.

Ex: To make a table that lists all department names along with the last name of the department
manager
SELECT DEPTNAME , LNAME
FROM DEPARTMENT , EMPLOYEE

31
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

WHERE DEPARTMENT.MANAGER = EMPLOYEE.EMPNO;

GROUP OR BUILT IN OR COLUMN FUNCTIONS

To perform calculations using SQL's group functions.


SQL supports the group functions
AVERAGE [AVG]
COUNT
MAXIMUM [MAX]
MINIMUM [MIN]
SUM

They all return a single value for the rows specified in the argument.
SYNTAX:
SELECT group function(column name) The group function goes
? ? in the SELECT statement
+-----------+ and is followed by the
¦ column to which it applies.
¦
+--------------- The column name must be
enclosed in parentheses.

SELECT GROUP FUNCTION1(COLUMN NAME),


GROUP FUNCTION2(COLUMN NAME),
.
.
You can use more than one group function. If you use a group function on one column then for
other columns you must either use a group function or have the columns included in the GROUP
BY clause.
You CANNOT mix a request for individual row values in the same SELECT statement.

The AVERAGE function


• Averages the specified values in the column.
• Column selected MUST contain numeric values.
• Arguments may be preceded by DISTINCT to eliminate duplicate values.
• The syntax for the Average function is :

SELECT AVG(column name)


FROM table

Ex: To find the average salary of all employees from the EMPLOYEE table.

SELECT AVG(SALARY) RESULT


FROM EMPLOYEE ; 32666.67
The result of this query is a table with one row and one column.

Ex: To find the average salary of all employees in DEPTNO 100 from the EMPLOYEE table.
SELECT AVG(SALARY)
FROM EMPLOYEE
WHERE DEPTNO = 100;
The WHERE clause tells SQL to average all values that meet the specified criteria .

32
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

The COUNT function

• Must be followed by the specification DISTINCT or *.


• COUNT(DISTINCT) returns the number of values in the column. No duplicates are counted.
• COUNT(*) counts all rows without eliminating duplicates.

The syntax for the Count function is :


SELECT COUNT(DISTINCT column name) or SELECT COUNT(*)

Ex: To find the number of departments in the EMPLOYEE table.


SELECT COUNT(DISTINCT DEPTNO)
FROM EMPLOYEE ;
The result of this query is 4.

SQL only counts each different value once. There are 4 unique values.
DEPTNO
100 <----
500 <----
300 <----
100
300
100
200 <----
500
100

MAX and MIN functions

• The MAX function returns the largest value in a column.


• The syntax for the MAX function is :
SELECT MAX(column name) FROM table
• The MIN function returns the smallest value in a column.
• The syntax for the MIN function is :
SELECT MIN(column name) FROM table

Ex: To find the minimum salary in the EMPLOYEE table.


SELECT MIN(SALARY)
FROM EMPLOYEE ;
In this case SQL returns the smallest value in the column.

Ex: To find the maximum salary in the EMPLOYEE table.


SELECT MAX(SALARY)
FROM EMPLOYEE ;
In this case SQL returns the Largest value in the column.

The SUM function


• Returns the sum of the values in the column
• Column selected MUST contain numeric value
• Arguments may be preceded by DISTINCT to eliminate duplicate values.
• The syntax for the SUM function is :
SELECT SUM(column name) FROM table

33
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Ex: To get the total salaries in the SALARY column for DEPTNO 100.These are found
in the EMPLOYEE table.

SELECT SUM(SALARY) RESULT


FROM EMPLOYEE ------
WHERE DEPTNO = 100 161000.00

The result is a table with one row and one column that gives the total salary of all employees in
department number 100.

Group functions return a single value for the rows specified. When using group functions in the
SELECT statement you cannot mix a query for individual values with one for group values.
SQL allows us to include an individual value column in the select statement if we are Grouping
on that column.

THIS QUERY IS NOT LEGAL BUT, THIS QUERY IS


------------------------ ------------------
SELECT DEPTNO, AVG(SALARY) SELECT DEPTNO, AVG(SALARY)
FROM EMPLOYEE; FROM EMPLOYEE
GROUP BY DEPTNO;

SELECT ... • MUST SPECIFY A BUILT IN FUNCTION


• MAY SELECT THE COLUMN IN THE GROUP BY CLAUSE

FROM ... • CODE THESE AS USUAL


WHERE ...

GROUP BY ... • MUST FOLLOW FROM AND WHERE AND PRECEDE ORDER BY
• MUST SPECIFY THE COLUMN YOU WANT TO SUMMARIZE
• CAN ONLY BE USED WHEN SELECT SPECIFIES A BUILT-IN FUNCTION.
EX:
SELECT DEPTNO, AVG(SALARY) SELECT DEPTNO, AVG(SALARY)
FROM EMPLOYEE FROM EMPLOYEE
GROUP BY DEPTNO WHERE SEX = 'F'
+------> GROUP BY DEPTNO
¦
THE RESULT OF THIS QUERY ¦ THE RESULT OF THIS QUERY
IS A TABLE THAT GIVES THE ¦ IS A TABLE THAT GIVES THE
AVERAGE SALARY FOR EACH +------- AVERAGE SALARY FOR FEMALES
DEPARTMENT. IN EACH DEPARTMENT.
+---------------+ +---------------+
¦DEPTNO¦ SALARY ¦ ¦DEPTNO¦ SALARY ¦
+------+--------¦ +------+--------¦
¦ 100 ¦40250.00¦ ¦ 100 ¦43000.00¦
¦ 200 ¦31000.00¦ ¦ 300 ¦30000.00¦
¦ 300 ¦29000.00¦ ¦ 500 ¦26000.00¦
¦ 500 ¦22000.00¦ +---------------+
+---------------+
If the command does not contain a WHERE clause the GROUP BY follows the FROM clause.
Otherwise the GROUP BY clause follows the WHERE clause.

Ex: Write a query that returns the number of employees in each DEPTNO from
the EMPLOYEE table.

SELECT DEPTNO, COUNT(*)


FROM EMPLOYEE

34
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

GROUP BY DEPTNO;

GROUP BY can also be followed by a HAVING clause, which is in some ways comparable to a
WHERE clause. The GROUP BY clause returns all groups in the result. Often we are only
interested in groups that meet certain criteria. To see only the groups of interest, you can specify
a search condition in a HAVING clause.
This statement:
• groups rows by department numbers
• performs the AVG group function
• tests each group for inclusion in the result
• returns only those groups that satisfy the condition .

SELECT DEPTNO, AVG(SALARY) SELECT DEPTNO, AVG(SALARY)


FROM EMPLOYEE FROM EMPLOYEE
GROUP BY DEPTNO WHERE SEX = 'F'
HAVING AVG(SALARY) > 30000.00 GROUP BY DEPTNO
HAVING AVG(SALARY) > 30000.00

HAVING determines which WHERE determines which


groups will be individual rows will
included be included

Rules for using a HAVING clause


HAVING can only be used with GROUP BY
HAVING must immediately follow the GROUP BY clause
HAVING can only compare built-in functions, not individual columns
EX:
SELECT DEPTNO, AVG(SALARY)
FROM EMPLOYEE
GROUP BY DEPTNO
HAVING COUNT (*) > 3;

COUNT was not included in the SELECT you can still use it in the HAVING clause.This query
will display the average salary for departments with more that 3 employees.

SUBQUERIES

Sub queries are powerful features of SQL.


Ex: To produce a table containing the last name, department number and salary of female
employees whose SALARY is greater than the average salary of male employees.

The first step is to find the average salary of male employees.


SELECT AVG(SALARY) RESULT
FROM EMPLOYEE ----------
WHERE SEX = 'M' 30400.00

The next step is to use this result by placing it in another query to find out which female
employees have a salary greater than the average salary for male employees.
RESULT
SELECT LNAME, DEPTNO, SALARY +------------------------+
FROM EMPLOYEE ¦ LNAME ¦DEPTNO¦ SALARY ¦
WHERE SEX = 'F' +--------+------+--------¦
AND SALARY > 30400.00; ¦JOHNSON ¦ 100 ¦48000.00¦
¦BAKER ¦ 100 ¦38000.00¦
+------------------------+

35
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Subqueries allow us to combine these two simple queries. The result of the subquery is evaluated
first since it needs the result to process the main query. To achieve the same result with only one
query.
SELECT LNAME, DEPTNO, SALARY
FROM EMPLOYEE
WHERE SEX = 'F'
AND SALARY >
(SELECT AVG(SALARY)
FROM EMPLOYEE
WHERE SEX = 'M');
Ex: Write the subquery required to list all employees who work in the same department as
Johnson.
SELECT LNAME, DEPTNO
FROM EMPLOYEE
WHERE DEPTNO IN
(SELECT DEPTNO
FROM EMPLOYEE
WHERE LNAME = 'JOHNSON')
Rules
Allow you to form complex queries out of several simple queries.
Must be enclosed in parentheses.
Follow the same general format as normal queries
SELECT ...
FROM ...
WHERE ...

May not have an ORDER BY clause.Allows only one column-name in its SELECT clause.
Processes the subquery first and passes the result to the main-query which then computes the
entire answer.Subqueries may contain multiple levels. When using more than one subquery, the
same rules apply and the format is the same.
Ex: To find the manager of the department where Mayr works, these are the steps we would
follow:
SELECT LNAME Result
FROM EMPLOYEE --------
WHERE EMPNO IN BAKER

(SELECT MANAGER Result


FROM DEPARTMENT --------
WHERE DEPTNO IN 737466

(SELECT DEPTNO Result


FROM EMPLOYEE -------
WHERE LNAME = 'MAYR')); 100
First SQL would search the employee table for the department number and pass it to the next
level. Next SQL would use the result to find the employee number of the manager from the
DEPARTMENT table. Finally SQL passes the EMPNO to the main query to find the manager's
name.

36
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

JOINS
SELECT * FROM PARTS;

PART PRODNO SUPPLIER


-------------------- ----------- --------------------
WIRE 10 AMCO
GLASS 35 BRADCO
PLASTIC 50 OK_CHEM
MAGNET 10 TURNER
BLADES 250 HOWARTH

SELECT * FROM PRODUCTS;

PRODNO PRODUCT PRICE


----------- -------------------- ----------
250 SAW 22.00
10 ALTERNATOR 55.50
45 PLIERS 75.75
50 RELAY 12.25

INNER JOIN
Two or more tables are joined together using the column having equal values among them.
SELECT A.PART, A.SUPPLIER, A.PRODNO, B.PRODUCT
FROM PARTS A
INNER JOIN PRODUCTS B
ON A.PRODNO = B.PRODNO

PART SUPPLIER PRODNO PRODUCT


-------------------- -------------------- ----------- --------------------
MAGNET TURNER 10 ALTERNATOR
WIRE AMCO 10 ALTERNATOR
PLASTIC OK_CHEM 50 RELAY
BLADES HOWARTH 250 SAW

LEFT OUTER JOIN


The clause LEFT OUTER JOIN includes rows from the table named before it where the values in
the joined columns are not matched by values in the joined columns of the table named after it.

SELECT A.PART, A.SUPPLIER, A.PRODNO, B.PRODUCT


FROM PARTS A
LEFT OUTER JOIN PRODUCTS B
ON A.PRODNO = B.PRODNO

PART SUPPLIER PRODNO PRODUCT


-------------------- -------------------- ----------- --------------------
MAGNET TURNER 10 ALTERNATOR
WIRE AMCO 10 ALTERNATOR
GLASS BRADCO 35 -
PLASTIC OK_CHEM 50 RELAY
BLADES HOWARTH 250 SAW

37
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

RIGHT OUTER JOIN


The clause RIGHT OUTER JOIN includes rows from the table named after it where the values in
the joined columns are not matched by values in the joined columns of the table named before it.

SELECT A.PART, A.SUPPLIER, A.PRODNO, B.PRODUCT


FROM PARTS A
RIGHT OUTER JOIN PRODUCTS B
ON A.PRODNO = B.PRODNO

PART SUPPLIER PRODNO PRODUCT


-------------------- -------------------- ----------- --------------------
MAGNET TURNER 10 ALTERNATOR
WIRE AMCO 10 ALTERNATOR
- - - PLIERS
PLASTIC OK_CHEM 50 RELAY
BLADES HOWARTH 250 SAW

FULL OUTER JOIN


The clause FULL OUTER JOIN includes unmatched rows from both tables. Missing values in a
row of the result table contain nulls.
SELECT A.PART, A.SUPPLIER, A.PRODNO, B.PRODUCT
FROM PARTS A
FULL OUTER JOIN PRODUCTS B
ON A.PRODNO = B.PRODNO

PART SUPPLIER PRODNO PRODUCT


-------------------- -------------------- ----------- --------------------
MAGNET TURNER 10 ALTERNATOR
WIRE AMCO 10 ALTERNATOR
GLASS BRADCO 35 -
- - - PLIERS
PLASTIC OK_CHEM 50 RELAY
BLADES HOWARTH 250 SAW

Union and Union All

Union
This command will allow you to combine result-set of two queries into single output.
It eliminate duplicates and gives unique rows.
SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2

Union All
This command will allow you to combine result-set of two queries into single output.
It gives duplicates into output and it is much faster than UNION.
SELECT column_name(s) FROM table_name1
UNION ALL
SELECT column_name(s) FROM table_name2

38
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Rules to code union/union all


1. Each query must have the same number of columns.
2. Each column must have compatible data types.
3. Column names for the final result set are taken from the first query.
4 .ORDER BY and COMPUTE clauses can only be issued for the overall result set and not
within each individual result set.
5. GROUP BY and HAVING clauses can only be issued for each individual result set and
not for the overall result set

How to combine two queries that has different set of columns


If you don't have the exact same columns in all queries use a default value or a NULL value such
as:
SELECT firstName, lastName, company FROM businessContacts
UNION ALL
SELECT firstName, lastName, NULL FROM nonBusinessContacts

Ex of Union and Union All


SELECT LNAME,DEPTNO LNAME DEPTNO
FROM EMPLOYEE JOHNSON 100
WHERE DEPTNO = '100'; LEBLANC 100
BAKER 100
MAYR 100

SELECT LNAME,DEPTNO LNAME DEPTNO


FROM EMPLOYEE JOHNSON 100
WHERE SALARY > 30000; LEBLANC 100
BAKER 100
SHELDON 200
MAYR 100

SELECT LNAME,DEPTNO LNAME DEPTNO


FROM EMPLOYEE JOHNSON 100
WHERE DEPTNO = '100'; LEBLANC 100
UNION ALL BAKER 100
SELECT LNAME,DEPTNO MAYR 100
FROM EMPLOYEE JOHNSON 100
WHERE SALARY > 30000; LEBLANC 100
BAKER 100
SHELDON 200
MAYR 100

SELECT LNAME,DEPTNO
FROM EMPLOYEE LNAME DEPTNO
WHERE DEPTNO = '100'; BAKER 100
UNION JOHNSON 100
SELECT LNAME,DEPTNO LEBLANC 100
FROM EMPLOYEE MAYR 100
WHERE SALARY > 30000; SHELDON 200

Ex of UNION from different tables


SELECT STUDENT_NAME, MOBILE_NUM SELECT STUDENT_NAME, MOBILE_NUM
FROM JUST_DIAL_ENQ UNION FROM OFFICE_ENQ
WHERE ENQ_DATE >= 20120101 WHERE ENQ_DATE >= 20120101

39
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

The UPDATE Statement


The UPDATE command is used to change the values in existing rows.
The general form is:
UPDATE table-name
SET column-name = newvalue
.
.
WHERE search condition
The set clause tells which columns to update and what values to change them to. To update
multiple columns in each row with a single UPDATE command by listing multiple columns in
the SET clause.
Ex.1:
UPDATE EMPLOYEE
SET SALARY = SALARY + 2000
WHERE EMPNO = 215012;

Ex.2: Write an UPDATE command to record a 10% increase in SALARY for everyone
in DEPTNO 100 in the EMPLOYEE table.

UPDATE EMPLOYEE
SET SALARY = SALARY * 1.1
WHERE DEPTNO = 100;

The DELETE statement


To removes one or more rows from a table a WHERE clause determines which rows are affected.
To delete all rows from a table omit the WHERE clause.

The general form is:


DELETE FROM table name
WHERE search condition

EX: DELETE
FROM EMPLOYEE
WHERE EMPNO = 737654;

EMBEDDED SQL

• Hard-coded into an application program


• cannot be modified during the program’s execution except for changes to the values assigned to
the host variables
• Cursors are used to access set-level data (i.e when a SQL SELECT returns more than 1 row)
The general form is
EXEC SQL
[SQL statements]
END-EXEC.

Embedded SQL statements always begin with EXEC SQL, and end with END-EXEC. There are
two important items in the WORKING STORAGE SECTION of a DB2 application program.

SQL Communications Area (SQLCA)


Declarations for Variables

40
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

SQL Communications Area (SQLCA)

An SQLCA is a structure or collection of variables that is updated after each SQL statement
executes. An application program that contains executable SQL statements must provide exactly
one SQLCA.
EXEC SQL INCLUDE SQLCA END-EXEC.
The "INCLUDE SQLCA" command merges the declaration of the SQL communications area
into your application program. This merge occurs when you precompile the application program.

Structure of the SQLCA (for COBOL)


01 SQLCA.
05 SQLCAID PIC X(8).
05 SQLCABC PIC S9(9) COMP.
05 SQLCODE PIC S9(9) COMP.
05 SQLERRM.
.
05 SQLERRD OCCURS 6 TIMES PIC S9(9) COMP.
05 SQLWARN.
10 SQLWARN0 PIC X(1).
10 SQLWARN1 PIC X(1).
.
.
10 SQLWARN7 PIC X(1).

SQLCODE
Each SQL statement is executed, a "return code" is placed in the SQLCODE. The value of
SQLCODE
0 : Successful SQL execution.
Positive Integer: Successful execution but an exceptional condition has occurred.
Negative Integer: An error has occurred, and no data has been moved.

SQLERRM
Whenever an error occurs, you will want to see the error message found in this SQLERRM field.
You should make use of the IBM supplied program, DSNTIAR, to display or record the
SQLERRM information.

SQLERRD(3)
It tells how many rows were modified by an INSERT, DELETE, or UPDATE statement.

SQLWARN
These warning fields are rarely used in most applications.

Declarations for Variables


EXEC SQL
INCLUDE EMPLOYEE
END-EXEC.
To use an "INCLUDE" for table declarations, you must have already generated and stored the
declarations. The tool for doing this is DB2I's DCLGEN.
DCLGEN
• Issued for a single table.
• Prepares the structures of the table in a COBOL copy book.
• The copy book contains a SQL DECLARE TABLE statement along with a working storage host
variable definition for the table

41
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Host Variables
Host variables must be declared in the application program. Host variables in an SQL statement
should have a colon added to its name as the first character.Host variables are used in SQL
statements for two main purposes:
1. The first use of a host variable is to specify a search condition.
MOVE '560983' TO EMPNO.
EXEC SQL
SELECT FNAME, LNAME
INTO :FNAME, :LNAME
FROM EMPLOYEE
WHERE EMPNO = :EMPNO
END-EXEC.
This SELECT uses the host variable :EMPNO, to find the record where :EMPNO='560983'

2. Host variables are used in another way in DB2 application programs. A host variable can be
used as a receiving variable, receiving data from a SELECT.
Ex: In the above SELECT Statement, Once the row has been selected where EMPNO = '560983',
data from the two columns, FNAME and LNAME, is placed into the host variables :FNAME
and :LNAME.

Null indicator

What is NULL
Null indicates an unknown value or value not known at this time.
Null increases business meaning i.e. one can easily write a query to find the null rows.
Ex: If a Bonus field of an employee table is null able, then it is easy to find the employees for
whom the bonus is not decided.
Null takes an extra byte to store the NULL value.
Ex: EMP_EMAIL CHAR(80)
If the employee has an email then it takes 80 bytes but internally it takes 81 bytes
If the employee email is not known at this time then it takes 1 byte internally.
Hexadecimal value of the first character of null is 'FF' and value is '00'.

How to handle null in SPUFI

How to insert Null


INSERT INTO EMPLOYEE (EMPNO,FNAME,DEPTNO,WPHONE,STARTDT,SEX,SALARY)
VALUES('307117',NULL,'JOHNSON ',NULL,'290-4788','1973-05-16','F',48000.00);

How to select all rows with NULL


SELECT * FROM EMPLOYEE
WHERE DEPTNO IS NULL

How to select all rows with NOT NULL


SELECT * FROM EMPLOYEE
WHERE FNAME IS NOT NULL

How to update with NULL


UPDATE EMPLOYEE
SET DEPTNO = NULL
WHERE EMPNO = '604985'

42
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

How to handle null in application program

How to select null fields

01 WS-IND PIC S9(4) COMP.

MOVE '307117' TO EMPNO


EXEC SQL
SELECT FNAME
INTO :FNAME :WS-IND
FROM EMPLOYEE
WHERE EMPNO = :EMPNO
END-EXEC

EVALUATE WS-IND
WHEN 0
DISPLAY 'FIRST NAME HAS VALUE'
WHEN -1
DISPLAY 'FIRST NAME HAS VALUE'
WHEN -2
DISPLAY 'FIRST NAME HAS VALUE BUT TRUNCATED BECAUSE HOST VARIABLE IS
SMALLER'
END-EVALUATE
Note: If the null is retrieved and null indicator is not used then it returns SQLCODE -305

How to retrieve null field without using null indicator


MOVE '307117' TO EMPNO
EXEC SQL
SELECT coalesce(FNAME,' ')
INTO :FNAME :WS-IND
FROM EMPLOYEE
WHERE EMPNO = :EMPNO
END-EXEC

How to update null fields

MOVE '604985' TO FNAME


MOVE -1 TO WS-IND

EXEC SQL
UPDATE EMPLOYEE
SET FNAME = :FNAME :WS-IND
WHERE EMPNO = :EMPNO
END-EXEC

Note: If you are trying to update a not null column with a null value then it returns sqlcode -407

VARCHAR

VARCHAR data type is used to save the memory when smaller length of the data is stored in a
field.
CHAR FIELD VARCHAR FILED
Field declaration: EMP_EMAIL CHAR(80) EMAIL_EMAIL VARCHAR(80)
Host variable: 05 EMP-EMAIL PIC X(80). 05 EMP-EMAIL.
49 EMP-EMAIL-LEN PIC S9(4) COMP.
49 EMP-EMAIL-TEXT PIC X(80).

43
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

How to update a varchar field

Here is an example: Read a FILE and update EMP_EMAIL column

FD IN-FILE.
01 IN-REC.
05 IN-EMP-NUM PIC X(4).
05 IN-EMAIL PIC X(80).
01 EMP-TBL.
05 EMP-NUM PIC X(4).
05 EMP-EMAIL.
49 EMP-EMAIL-LEN PIC S9(4) COMP.
49 EMP-EMAIL-TEXT PIC X(80).

01 STOP-LOOP PIC X(1) value 'n'.


01 WS-COUNT PIC S9(4) COMP VALUE zeros.

READ IN-FILE
MOVE 'N' TO STOP-LOOP
PERFORM VARYING WS-COUNT FROM 80 BY -1 UNTIL WS-COUNT < 1
OR STOP-LOOP = 'Y'
IF IN-EMAIL(WS-COUNT:1) > SPACE
MOVE WS-COUNT TO EMP-EMAIL-LEN  It removes trailing spaces and moves
MOVE 'Y' TO STOP-LOOP actual length of the email
END-IF
END-PERFORM
MOVE IN-EMAIL TO EMP-EMAIL-TEXT  Text is moved here
MOVE IN-EMP-NUM to EMP-NUM
EXEC SQL
UPDATE EMP
SET EMP_EMAIL = :EMP-EMAIL  Group field is used here
WHERE EMP_NUM = :EMP-NUM
END-EXEC.

If the actual length of the email is 40 then the column is written with 40 bytes
If the actual length of the email is 80 then the column is written with 80 bytes
Internally, varchar takes two extra bytes to store the length.
If most of the emails are close to the right limit (i.e. 80 characters) then use CHAR instead of
VARCHAR

COMMIT
Commit operates on a unit of recovery after executing this statement
All changes will be done permanently.
Row locks will be released .
Default commit is at program termination.
Cursors are closed except those declares with hold option.
Syntax:
EXEC SQL
COMMIT[WORK]
END-EXEC.

ROLLBACK
A unit of work is undone if any abnormal condition occurs. when the statement is executed
All changes in that unit of work be backed out,
All locks are released and all open cursors are closed.

44
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

When you issue a rollback then the database manager will re-establish the state of the database at
the last completed unit of work.
Rollback will be done either by the program or by the system.
Syntax:
EXEC SQL
ROLLBACK [WORK]
END-EXEC.

CURSORS

What is cursor and when is it used


Cursor is a resultant table of a select query. Cursor is used in the application program when the
Select query is returning more than one row.
In a Select query, When a where condition is used with equal operator on unique column, then it
will return single row. In all other cases it may return multiple rows. Use a singleton query in the
first case and use a cursor in the second case.

What are different steps involved in using CUSORS


There are four steps involved in using CUSORS.
1. Declare cursor  It can be declared either in WS section/Procedure division
2. Open Cursor  It should be coded in Procedure division
3. Fetch Cursor  It should be coded in Procedure division
4. Close Cursor  It should be coded in Procedure division

DECALRE Cursor
It is a declarative statement and it can be declared either working storage section or procedure
division. If it is declared in the procedure division, then declare it before OPEN Cursor statement.
It is recommended to declare in the working storage section.
Syntax Example
EXEC SQL DECLARE Cursorname CURSOR FOR EXEC SQL DECLARE cur1 CURSOR FOR
SELECT col1, col2, col3... SELECT emp_no,emp_name,dept_no,emp_sal
FROM Tablename FROM emp
[WHERE condition] WHERE dept_no = :dept-no
END-EXEC. END-EXEC.

Note: INTO clause is not used in the cursor declaration because cursor is not executed here.

OPEN Cursor
It is an executable statement and it should be declared in procedure division before FETCH
Cursor. Select statement in a cursor is executed here and returns resultant rows into cursor
table(resultant table). Move values to the host variables given in the where condition before the
OPEN cursor statement.
Open cursor generates resultant table but are not returned to host variables of the program.
Syntax Example
Move values to the host variable of MOVE 100 to dept-no
where condition

EXEC SQL OPEN Cursorname EXEC SQL OPEN cur1


END-EXEC END-EXEC

FETCH Cursor

45
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Rows from resultant table are returned to the host variables in this statement.One FETCH
statement returns one row from resultant table to host variables.
Repeat the FETCH process until end of resultant table.
Syntax Example
PERFORM UNTIL SQLCODE = 100 PERFORM UNTIL SQLCODE = 100
EXEC SQL FETCH Cursorname EXEC SQL FETCH cur1
INTO :col1, INTO :emp-no,
:col2, :emp-name,
:col3, :dept_no,
. :emp-sal
. END-EXEC
END-EXEC IF SQLCODE = 0
END-PERFORM PERFORM PROCESS-PARA
END-IF
END-PERFORM
CLOSE Cursor
Close the cursor after completion of FETCH process. Cursor can be opened again with different
values after CLOSE cursor.
Syntax Example

EXEC SQL CLOSE Cursorname EXEC SQL CLOSE cur1


END-EXEC END-EXEC

Different options in Cursors

1. FOR UPDADTE OF col1, col2.. and WHERE CURRENT OF

FOR UPDATE OF clause is used to update the fetched rows of cursor.


Requirement
Hike the salary of employees by 10% in the department 300 and write ouput file with old
salary and new salary.
EXEC SQL DECLARE cur1 CUROSR FOR
SELECT emp_no, emp_sal
FROM emp
WHERE dept_no = :dept-no
END-EXEC
.
.
MOVE 300 TO dept-no

EXEC SQL
OPEN cur1
END-EXEC

PERFORM UNTIL SQLCODE = 100


EXEC SQL FETCH cur1
INTO :emp-no,
:emp-sal
END-EXEC

IF SQLCODE = 0
MOVE emp-no TO out-emp-no
MOVE emp-salary TO out-old-salary
COMPUTE out-new-salary = emp-salary * 1.1
WRITE out-rec

EXEC SQL
UPDATE emp

46
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

SET emp-sal = emp-sal * 1.1


WHERE CURRENT OF cur1
END-EXEC
END-IF
END-PERFORM

EXEC SQL
CLOSE cur1
END-EXEC

NOTE:
1. FOR UPDATE OF cannot be used when a cursor is declared with JOINS. In that case update
the selected rows with where condition but not WHERE CURRENT OF.

Delete a record which is just fetched


Delete the record which is just fetched with ‘WHERE CURRENT OF’ clause. ’WHERE
CURRENT OF’ clause can also be used in delete statement without declaring ‘FOR UPDATE
OF’ clause in cursor declaration.
Syntax:
EXEC SQL
DELETE FROM tbl1
WHERE CURRENT OF Cur1
END-EXEC

2. WITH HOLD
Cursor will be closed automatically when a commit/rollback is used. When WITH HOLD is
used, cursor will not be closed when Commit/Rollback is used.
EXEC SQL DECLARE cur1 WITH HOLD FOR
SELECT emp_no, emp_sal
FROM emp
WHERE dept_no = :dept-no
END-EXEC

SQLCODES on CURSORS

-500  Fetch or close on a closed cursor that is declared with WITH HOLD option.
-501  Fetch or close on a closed cursor.
-502  Open on opened cursor
-503  A column cannot be updated by using WHERE CURRENT OF clause because FOR
UPDATE OF clause is not coded in the cursor declaration
-504  Opening a cursor but cursor is not declared
Cursor is declared after open statement
-507  Update or delete by using WHERE CURRENT OF clause but cursor is not opened
-508  Update or delete by using WHERE CURRENT OF clause but the fetched row is deleted
by another SQL Statement. Update or delete but prior fetch is not success.
-509  Update or delete by using WHERE CURRENT OF clause but cursor is not declared
on that table.
-510  Update or delete by using WHERE CURRENT OF clause but cursor is declared as
shown below.
1. Declared with FOR FETCH ONLY option.
2. Declared on multiple tables by using joins.
3. Declared on non-updatable views.

DB2 PROGRAM PREPARATION

47
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

+-------------+
¦ Source Code ¦ sourcelib(mem)
+-------------+
¦
(Modified source) +----------------+ (Extracted SQL
¦ DSNHPC ¦ statements)
+--------¦ Pre-Compiler ¦--------+
¦ +----------------+ ¦
¦ ¦
¦ ¦
+-----------+ +-----------+
¦ IGYCRCTL ¦ +---- ¦ DBRMs ¦ (DBRM library that
¦ Compile ¦ ¦ +-----------+ collects members)
+-----------+ ¦ ¦
¦ ¦ +-------------+ (Bind one DBRM mem
+-----------+ ¦ ¦ IKJEFT01 ¦ to one package)
¦ IEWL ¦ ¦ ¦ Bind Package¦
¦ Link Edit ¦ ¦ +-------------+
+-----------+ ¦ ¦
¦ ¦ +-------------+ (Bind packages or
Loadlib(mem) ¦ ¦ IKJEFT01 ¦ DBRM members to
+----¦ Bind Plan ¦ plan)
+-------------+

Steps to execute a COBOL+DB2 program

1. Create Source PDS, Copy library, DBRM Library, Load library


2. Create Table and Index in SPUFI/QMF
3. Create copybook for the table in Copy library from DCLGEN
4. Write a COBOL + DB2 program based on the requirement
a. Define table copybook created in DCLGEN with INCLUDE statement
Ex: Include DCLEMP
b. Define system defined copybook SQLCA
Ex: Include SQLCA
c. Code embedded SQL statements in delimiters
EXEC SQL
Select emp_num, emp_sal into :emp-num, :emp-sal
From EMP Where emp_num = :emp-num
END-EXEC.
5. Prepare COBOL+DB2 program with the below steps
PGM1
Pre-compile

Compile Bind Package

Link edit Bind Plan

Userid.loadlib1 (PGM1) Plan1

6. Create RUN JCL to execute COBOL+DB2 program

48
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

//step1 EXEC PGM=IKJEFT01


//infile dd dsn=file1,disp=shr
//outfile dd dsn=file2,disp(new,catlg,delete)
// unit=sysda,space=(cyl,(10,5),rlse)
// dcb=(recfm=fb,lrecl=100,blksize=0)
//systsin dd *
DSN System(DB2T)
Run Program(PGM1) Plan(PLAN1) Library(userid.loadlib1)
/*
7. Prepare test data into input DB2 tables and input files
Enter data in tables in below methods
a. Execute Insert statement from SPUFI/QMF
b. Edit data from File aid DB2
c. Load data from PS to Table in batch with DSNUTILB
8. Execute RUN JCL and check the results

COBOL+DB2 compile JCL

//OZAXXXPC JOB (99012T),'MADHU PADALA',


// CLASS=A,MSGCLASS=X,REGION=0M,NOTIFY=&SYSUID
//*
//PRECOMP EXEC PGM=DSNHPC,PARM='HOST(IBMCOB),SOURCE'  precompile step
//SYSIN DD DISP=SHR,DSN=OZAXXX.SMF.SRCLIB(PGM1)  Source code
//SYSLIB DD DISP=SHR,DSN=OZAXXX.SMF.DB2.COPYLIB  DCLGEN Copy Library
//DBRMLIB DD DISP=SHR,DSN=OZAXXX.SMF.DBRMLIB(PGM1)  DBRM into DBRM Library
//SYSCIN DD DSN=&&TEMP1,DISP=(MOD,PASS),UNIT=SYSDA,Modified Source
// SPACE=(CYL,(1,1))
//SYSUT1 DD SPACE=(CYL,(1,1),,,ROUND),UNIT=SYSDA
//SYSUT2 DD SPACE=(CYL,(1,1),,,ROUND),UNIT=SYSDA
//SYSPRINT DD SYSOUT=*  Precompile listing
//SYSTERM DD SYSOUT=*
//*
//COMPILE EXEC PGM=IGYCRCTL,PARM='APOST',COND=(4,LT,PRECOMP)  compile step
//STEPLIB DD DSN=IGY.SIGYCOMP,DISP=SHR
//SYSIN DD DSN=&&TEMP1,DISP=(OLD,DELETE) Modified source from PRECOMPILE
//SYSLIB DD DSN=OZAXXX.SMF.COBOL.COPYLIB,DISP=SHR  COBOL Copy Library
//SYSLIN DD DSN=&&TEMP2,UNIT=SYSDA,DISP=(MOD,PASS),  Object code
// SPACE=(CYL,(1,1))
//SYSUT1 DD UNIT=SYSDA,SPACE=(CYL,(1,1))
//SYSUT2 DD UNIT=SYSDA,SPACE=(CYL,(1,1))
//SYSUT3 DD UNIT=SYSDA,SPACE=(CYL,(1,1))
//SYSUT4 DD UNIT=SYSDA,SPACE=(CYL,(1,1))
//SYSUT5 DD UNIT=SYSDA,SPACE=(CYL,(1,1))
//SYSUT6 DD UNIT=SYSDA,SPACE=(CYL,(1,1))
//SYSUT7 DD UNIT=SYSDA,SPACE=(CYL,(1,1))
//SYSPRINT DD SYSOUT=*  Compile listing
//SYSOUT DD SYSOUT=*
//*
//LKED EXEC PGM=IEWL, PARM='AMODE(31), RMODE=ANY',  Link edit step
// COND=(4,LT,COMPILE)
//SYSLIN DD DSNAME=&&TEMP2,DISP=(OLD,DELETE)  Object code from compile
// DD DDNAME=SYSIN

//SYSLIB DD DSN=OZAXXX.SMF.LOADLIB,DISP=SHR  Subprogram Load Library

49
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

// DD DSN=CEE.SCEELKED,DISP=SHR
// DD DSN=DSN710.SDSNLOAD,DISP=SHR
//SYSLMOD DD DSN=OZAXXX.SMF.LOADLIB(PGM1),DISP=SHR  Load module
//SYSUT1 DD UNIT=SYSDA,SPACE=(CYL,(1,1))
//SYSPRINT DD SYSOUT=*
//SYSIN DD *
NAME PGM1(R)
/*
//*
//BINDPLAN EXEC PGM=IKJEFT01  Bind plan step
//DBRMLIB DD DISP=SHR,DSN=OZAXXX.SMF.DBRMLIB  DBRM Library from PRECOMP
//SYSPRINT DD SYSOUT=*
//SYSTSPRT DD SYSOUT=*
//SYSUDUMP DD SYSOUT=*
//SYSTSIN DD *
DSN SYSTEM(DSN)
BIND PLAN(PLAN1) -  PLAN
MEMBER(PGM1) -
ACT(REP) -
ISOLATION(CS) -
VALIDATE(BIND) -
EXPLAIN(NO)
END
/*

Run JCL
//OZAXXXRN JOB OZA,OZA,MSGLEVEL=(1,1),
// CLASS=A,MSGCLASS=A,NOTIFY=&SYSUID,REGION=6M
//*
//STEP1 EXEC PGM=IKJEFT01,DYNAMNBR=20
//SYSTSPRT DD SYSOUT=*
//SYSPRINT DD SYSOUT=*
//SYSUDUMP DD SYSOUT=*
//SYSOUT DD SYSOUT=*
//SYSTSIN DD *
DSN SYSTEM(DSN)  DB2 Subsystem name
RUN PROGRAM(PGM1) PLAN(PLAN1) -  Program name and plan name
LIB('OZAXXX.SMF.LOADLIB')  Load library of the program
END
/*

Precompile

Different activities of precompilation


COBOL compiler doesn't know about Sql statements, with this reason cobol db2 program has to
undergo with precompilation. Precompile does the following activities

1. Expands all copybooks declared with include statement


2. Validates table declaration used in the DCLGEN copybook
3. Checks Syntactical errors on SQL statements and also validates the fields
based on table declaration from DCLGEN copybook
4. Extracts all sql statements into DBRM and replaces sql statements with
COBOL Call statements (CALL 'DSNHLI' using..).
COBOL code which is replaced with CALL statements is called modified source

50
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

5. Generates Timestamp for both modified source and DBRM. These are checked
in the run time.
Note: Precompilation can be executed even if DB2 is down.
Table validations are done based on dclgen copybook but not from the DB2 catalog entries.
Note: Supply only Dclgen copybooks in SYSLIB of precompilation step

Compile
It is same as normal COBOL compilation. It takes modified source as input and compiles. Supply
Copy copybooks in this step. Output of this compilation is object module.

Linkedit
This takes object module from compile step and also takes sub program load modules and
generates load module.

Bind
DBRM which is extracted in the precompilation is not an executable. It has to undergo through
BIND process which makes statements executable.

Activities of Bind process


1. Checks SQL statements with the DB2 cataloged entries.
2. Checks authorization of the programmer on the sql statements
3. Gets optimized access path from the statistics of the runstats. It gets best indexed path if the
indexes are built. This improves these SQL performance improvement of bind process in
different evolutions.

1. Bind all DBRM members directly to the PLAN.

Disadvantages
When a new program is to be bound to the existing plan or changes are done in the existing
program which is bound to a plan then BIND PLAN has to be executed. Even though single
elements has to be bound, all elements which were already bound to the plan are bound once
again

2. Bind one DBRM in to a one package and then all packages bind to PLAN

Bind package
Bind package is almost similar to bind plan. Bind package means transferring bind activities
from plan to a package and this package is executed from plan

Improvement in the second evolution


When existing program is impacted then bind that package only. In the run time the plan picks up
the updated package. So, no need to bind other packages which are bound to the plan.

Disadvantage
When a new program is created and this is to be executed with existing plan, then bind this
program to a new package and then bind plan by including this package. So, bind plan is
required when a new program is created.

51
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

3. Bind one DBRM to one package and group packages into a collection.
Bind package with Collection ID. Bind plan with collections. Collection is not a physical object
it is logical name.

Improvement in the third evolution


When a new program is created which is bind with a new package and grouped to existing
collection. Then bind plan is not required. Bind plan is done only one time. As long as packages
are bound to the existing collections Bind plan is not required. When new collections are
introduced then go for bind plan.

Conclusion:
Evolution1
When members directly bound to plan, then if existing member modified or new member is
created then bind the plan.

Evolution2
When packages are directly bound to plan, then if the existing members are modified then it is
required to bind package only. If a new member is created then it is required to bind package and
then bind plan.

Evolution3
When packages are indirectly bound to plan with collection id, then if the existing package is
modified or new package is created to the existing collections then bind package is enough, bind
plan is not required.

How the program preparation done with ENDEVOR

1. Add COBOL-DB2 program to Endevor. Endevor does the following activities.


a) Precompile which creates DBRM member into DBRM library.
b) Compile
c) Linkedit
2. Bind DBRM member to a package with SPUFI or external bind JCL

Bind parameters

Isolation(CS/RR/UR)
CS - Cursor stability
When a row is selected then it applies lock on the page. When it moves the next row which is on
another page then the lock held on first page is released and it is held on second page. When a
row is updated then the page is locked until commit is issued. Most of real applications use this
option. With this more concurrency is achieved.

RR - Repeatable Read
When a row is read then page is locked until the next commit point. All rows that are read are
locked until next commit point. When program wants to read the same record again and again
then that should not be modified another program. When mass updates are required then this
option is used. With this concurrency is reduced.

52
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

UR - Uncommitted read/ Dirty read


It does not hold any locks on the table. It can read the uncommitted rows (Rows that are updated
but not committed). Once after reading the row, then other program can rollback the updates done
on the row. Accessing data is faster but you may get incorrect data. After the record is read

Isolation Examples

Bind Parameters
RR/RS/CS/UR

Select *
From Theater
Where Class = 'F' and
Booked_status = 'N'
Seat_no between 001 and 100
The above query is executed by USER1.Seat numbers 007, 009, 025, 027, 035 are selected for the
above selection

RR  User1 can see 5 records and these are locked by share lock i.e. others can browse the data
in a share lock but they cannot update these. Only User1 can update above 5 records.
If user1 updates any ticket then that record cannot be viewed by other users because it turns into
Exclusive lock. This can be viewed by other user with UR.
Other users can browse other 95 records in share lock i.e. they can read but not update
If User1 executes the same query again and again before commit point but it returns the same
number of records that he got for the first time.

RS  User1 can see 5 records and these are locked by share lock i.e. others can browse the data
in a share lock but they cannot update these. Only User1 can update above 5 records
If user1 updates any ticket then that record cannot be viewed by other users because it turns into
Exclusive lock. This can be viewed by other user with UR.
Other users can edit other 95 records if it is not reducing user1's output. Other users can cancel
the tickets that are already booked.
If User1 executes the same query again and again before commit point then it should return >=5
records but not less than 5

CS  5 records are selected but the record on which the cursor is placed is locked by share lock.
If the record is simply read and moved to the next record then lock is held on second record and
lock release on the first record.
If the record is updated and moved to the next record then lock is held on first record until the
commit point.

UR  User1 can read 5 records even these are locked by other users with CS/RR/RS.
While user1 is looking into these five records; others can also update these records.

Validate (BIND/RUN)
Default -> RUN It Validates db2 objects either bind time or run time. Validate bind time is
always better because it reduces burden at run time. Also if it is at bind time, then it will be done
one time. If it is given at run time then validation will be done for every run.

53
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Action (ADD/Replace)
Default -> REPLACE

ADD
Add member to package or plan. It fails if the members is already bound. Replace It will add
member to package or plan if it is first time otherwise it will replace the existing member.

EXPLAIN (YES/NO)
Default -> NO
It will explain about the access path that is taken into User_Plan if YES is given.

Qualifier
If the qualifier is used for every table then if that qualifier is given in the Qualifier option then it
is not required to code for every table in the program. Actual table name is MNT1.EMP
Qualifier(MNT1) Then you can write in the program like it is shown below
EXEC SQL
Select *
Into :Emp-num,
:Emp-name,
:Emp-sal
From EMP
Where Emp_num = :Emp-num
END-EXEC

If the qualifier is not given in the Bind then you have to use like it is shown below
EXEC SQL
Select *
Into :Emp-num,
:Emp-name,
:Emp-sal
From MNT1.EMP
Where Emp_num = :Emp-num
END-EXEC
Then it is not required to give MNT1

ACQUIRE(USE) RELEASE(COMMIT)
DB2 imposes TABLE or TABLESPACE lock when it executes an SQL statements that
references a table in the table space and it release the acquired lock on COMMIT or
ROLLBACK.This is default option and provides greater concurrency.

Show Bind cards and Run card


________________________________________________________________________
| Bind package | Bind Plan | Run |
| IKJEFT01 | IKJEFT01 | IKJEFT01 |
|_________________________|_______________________|______________________________|
|//SYSTSIN DD * | //SYSTSIN DD * |//SYSTSIN DD * |
| DSN SYSTEM(DB2T) | DSN SYSTEM(DB2T) | DSN SYSTEM(DB2T) |
| BIND PACKAGE(COLL1) - | BIND PLAN(PLAN1) - | RUN PROGRAM(PGM1) - |
| MEMBER(PGM1) - | PKLIST(COLL1.*, - | PLAN(PLAN1) - |
| ACT(REP) - | COLL2.*) - | LIB('TSO.USERID.LOADLIB') |
| ISOLATION(CS) - | ACT(REP) - | |
| VALIDATE(BIND) - | ISOLATION(CS) - | END |
| EXPLAIN(NO) | VALIDATE(BIND) - |/* |
| | EXPLAIN(NO) | |
| END | | |
|/* | END | |
| | /* | |
|_________________________|_______________________|______________________________|

54
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Dynamic Sql

What is dynamic SQL


It is a concept of application program. The SQL statement is prepared and executed in the run
time.

Difference between Static SQL and Dynamic SQL


Static SQL Dynamic SQL
1. Object and action of a query is known 1. Object or action of a query is not known
2. Statement is prepared at the time the 2. Statement is prepared at run time
program is written
3. Syntax checking of statement is done 3. Syntax checking and binding is done at
at precompile time and bound at run time. It is done for every run.
bind time. It is bound one time.
4. It is faster than dynamic sql 4. It is slower than Static SQL
5. It generates sql codes for run time 5. It generates sqlcodes for both compile
errors time errors and run time errors
Ex: Incorrect column name is specified. Ex: Incorrect column name is specified.
This is a compile time error but This is a run time error.
not run time error.
6. It is highly used in applications 6. It is rarely used in real applications

Coding a Dynamic SQL


1. Translate the input data into SQL statement
2. Prepare the SQL statement to execute
3. Execute SQL statement
4. Handle SQL return codes
5. Process the information returned

Translate the input data into SQL statement


1. Declare variable as shown below.
2. Move statement and length in the text and length field as shown.
01 WS-STMT.
05 WS-STMT-LEN PIC S9(04) COMP.
05 WS-STMT-TEXT PIC X(50).

MOVE ‘DELETE FROM EMPLOYEE’ TO WS-STMT-TEXT.


MOVE 50 TO WS-STMT-LEN.

Execute Immediate in a Dynamic SQL


Execute immediate is used when there are no host variables in the SQL statement

01 WS-STMT.
05 WS-STMT-LEN PIC S9(04) COMP.
05 WS-STMT-TEXT PIC X(50).

MOVE ‘DELETE FROM EMPLOYEE’ TO WS-STMT-TEXT.


MOVE 50 TO WS-STMT-LEN.

EXEC SQL
EXECUTE IMMEDIATE :WS-STMT
END-EXEC.

55
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Parameter makers
Host variables cannot be used in statement that is moved to the text field.
Use parameter makers if a host variable is required in the statement as shown below.
Move 'DELETE FROM EMPLOYEE WHERE EMPNO = ?' to WS-STMT-TEXT

Prepare once
EXEC SQL
PREPARE S1 FROM :WS-STMT
END-EXEC.

Execute many times


Read In-file
Move in-empno to WS-EMPNO
EXEC SQL
EXECUTE S1 USING :WS-EMPNO
END-EXEC.

Dynamic SQL for Cursor


1. Declare cursor
2. prepare statement for cursor
3. Open cursor
4. Fetch cursor until sqlcode = 100
5. Close cursor

Declare Cursor
EXEC SQL
DECLARE C1 CURSOR FOR STMT
END-EXEC.

Prepare Statment for curosr


MOVE 'SELECT empno, empsal, deptno FROM EMPLOYEE WHERE deptno = ?'
TO WS-STMT-TEXT
MOVE 50 to WS-STMT-LEN
EXEC SQL
PREPARE STMT FOR :WS-STMT
END-EXEC.

Open Cursor
MOVE '100' to ws-deptno
EXEC SQL
OPEN C1 USING :ws-deptno
END-EXEC.

Fetch cursor
Perform until SQLCODE = 100
EXEC SQL
FETCH C1 INTO :EMPNO, :EMPSAL, :DEPTNO
END-EXEC.
If SQLCODE = 0
Perform Process-para
End-if
End-Perform

Close Cursor
EXEC SQL
CLOSE C1
END-EXEC.

56
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Grant
Grant is used to give the authorizations on a table/view to the other users/group/public.
General syntax:
GRANT ALL ON TABLE table-name/view-name TO USER/GROUP/PUBLIC [WITH GRANT
OPTION]

ALTER
CONTROL
DELETE
INDEX
INSERT
REFERENCES
SELECT
UPDATE (COLUMN)

ALTER grants the following privileges


. Ability to Add/drop/alter a column
. Ability to Add/drop primary key, foreign key
. Ability to Add check/unique constraint
. Ability to Create a trigger

CONTROL grants the following privileges


. Ability to Alter, Control, Delete, Insert, references, select and update to base tables
. Ability to Control, Delete, Insert, Select and update on views
. Ability to execute runstats and reorg
. Ability to grant the above privileges to others

DELETE grants the privilege to delete rows from the table or updatable view
. Ability to delete rows from table and updatable views

INDEX grants the privilege to create index on the table


. Ability to create or drop indexes on the table

INSERT
. Ability to insert rows into table and updatable views

REFERENCES
. Ability to create or drop foreign keys

SELECT
. Ability to select data from the table
. Ability to create view on the table

Update
. Ability to update either all columns or columns specified in Grant option

WITH GRANT OPTION


. Ability for the grantee to grant privileges to others

57
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Examples:

Grant ALL accesses on EMPLOYEE table to single user USER1


GRANT SELECT ON employee TO USER user1

Grant Select access on EMPLOYEE table to single user USER1


GRANT SELECT ON employee TO USER USER1

Grant Select access on EMPLOYEE table to single user USER1 and USER1 can give
select grant to others
GRANT SELECT ON employee TO USER user1 WITH GRANT OPTION

Grant Select access on EMPLOYEE table to all users under group GROUP1
GRANT SELECT ON employee TO GROUP group1

Grant Select and update access on STAFF table to all users under group GROUP1
GRANT SELECT,UPDATE ON TABLE staff TO GROUP group1

Grant insert access on EMPLOYEE table to all users in the system


GRANT INSERT ON TABLE employee TO PUBLIC

Revoke

Revoke is used to take privileges on table/view from users/group/public.


General syntax:
REVOKE ALL ON TABLE table-name/view-name FROM USER/GROUP/PUBLIC

ALTER
CONTROL
DELETE
INDEX
INSERT
REFERENCES
SELECT
UPDATE (COLUMN)

Examples:

Revoke Select access on EMPLOYEE table from user USER1


REVOKE SELECT ON employee FROM USER user1

Revoke Select access on SYSCAT.TABAUTH table from user USER1


REVOKE SELECT ON TABLE SYSCAT.TABAUTH FROM PUBLIC

58
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Trigger

What is a Trigger?
A trigger is a specialized program that is not called directly, but is event-driven.
When a data modification statement, such as an insert or an update, occurs, a trigger is executed,
or “fired”, which may make other database updates or call a stored procedure.
A trigger is not directly called or executed. After being created, it is always executed when its
firing event occurs. DB2 version 5 does not support triggers.

Why Use Triggers?


1. Support data integrity – if a change to one column dictates a change to another, a trigger
ensures they always stay in sync.
2. Simplify scheduling – if an action needs to happen every time a particular column is updated,
the trigger avoids having to schedule it.
3. Support complex business rules – having business rules in the database ensures everyone uses
the same logic to accomplish the same process.

CREATE TRIGGER Sample SQL (DB2)


The following examples show sample SQL code for creating different types of DB2 triggers.

Example 1
Create two triggers that will result in the automatic tracking of the number of employees a
company manages. The triggers will interact with the following tables:

EMPLOYEE table with these columns: ID, NAME, ADDRESS, and POSITION.
COMPANY_STATS table with these columns: NBEMP, NBPRODUCT, and REVENUE.

The first trigger increments the number of employees each time a new person is hired; that is,
each time a new row is inserted into the EMPLOYEE table:
CREATE TRIGGER NEW_HIRED
AFTER INSERT ON EMPLOYEE
FOR EACH ROW MODE DB2SQL
UPDATE COMPANY_STATS SET NBEMP = NBEMP + 1

The second trigger decrements the number of employees each time an employee leaves the
company; that is, each time a row is deleted from the table EMPLOYEE:
CREATE TRIGGER FORMER_EMP
AFTER DELETE ON EMPLOYEE
FOR EACH ROW MODE DB2SQL
UPDATE COMPANY_STATS SET NBEMP = NBEMP - 1

Example 2
Create a trigger that ensures that whenever a parts record is updated, the following check and (if
necessary) action is taken:
If the on-hand quantity is less than 10% of the maximum stocked quantity, then issue a shipping
request ordering the number of items for the affected part to be equal to the maximum stocked
quantity minus the on-hand quantity.
The trigger will interact with the PARTS table with these columns: PARTNO, DESCRIPTION,
ON_HAND, MAX_STOCKED, and PRICE.
ISSUE_SHIP_REQUEST is a user-defined function that sends an order form for additional parts
to the appropriate company.

CREATE TRIGGER REORDER

59
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

AFTER UPDATE OF ON_HAND, MAX_STOCKED ON PARTS


REFERENCING NEW AS N
FOR EACH ROW
WHEN (N.ON_HAND < 0.10 * N.MAX_STOCKED)
BEGIN ATOMIC
VALUES(ISSUE_SHIP_REQUEST(N.MAX_STOCKED - N.ON_HAND, N.PARTNO));
END

Example 3
Create a trigger that will cause an error when an update occurs that would result in a salary
increase greater than ten percent of the current salary.
CREATE TRIGGER RAISE_LIMIT
AFTER UPDATE OF SALARY ON EMPLOYEE
REFERENCING NEW AS N OLD AS O
FOR EACH ROW MODE DB2SQL
WHEN (N.SALARY > 1.1 * O.SALARY)
SIGNAL SQLSTATE '75000' SET MESSAGE_TEXT='Salary increase>10%'

Performance guide lines

1. pre test all your queries in SPUFI/QMF before used in the program
2. Use Qualifies in the bind and Avoid it in the program
3. Code most restrictive predicate first
4. Create index on predicates, Group by columns, orderby columns, join columns
5. Prefer IN clause instead of multiple OR conditions
6. If possible, Use Joins in the place of subquery
7. Go for runstats and rebind after large updates, inserts
8. Don’t use SELECT *. It increases program maintenance when a new field is added and
that is not required in few programs.
9. Do the arithmetic and string manipulation in the query rather than programming language.
10. Avoid Usage of NOT = except in NOT EXITS
11. Use for Fetch only in the cursor declaration, if the rows are not updatable.
12. Use UR in the BIND option for report programs, so that it will not lock any records.
But make sure other update jobs are not running at that time.
13. Use multicolumn index instead of multiple indexes
14. Do not use arithmetic operations in predicate, because it will not use indexes.
15. Minimize number of tables in Join.
16. Use BETWEEN clause instead of >= and <=
17. Use CHAR instead of VARCHAR on small fields
18. Use Where EXISTS (Select 1 from tab) to check the existence of a row.
19. Apply a commits and restart logic on mass update programs.

Explain

60
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

When an SQL is executed against or bound to a DB2 database DB2, Optimizer tool defines the
access path used to access the data. This access path is defined according to tables’ statistics
generated by DB2 Runstats tool.
The Explain command details the access path defined by DB2 and allows you to analyze how the
data will be accessed and how you can improve the command’s performance.

Steps required to find the access path


3 steps required to find the access path used for the given SQL statement.
Step1:
• Create a PLAN_TABLE on userid like OZA183.PLAN_TABLE. Here OZA183 is a userid.
• Create this table with 51 columns prior to Version 8 and 58 columns after Version 8.
• Table definition can be copied from the IBM’s Public library site.
• You can also create this table from other users with the below command.
CREATE TABLE User1.PLAN_TABLE AS user2.PLAN_TABLE
• Create table is one time activity and this table can be used for ever to explain access path of
any query.

Step2:
Execute the explain command on your selection command:
EXPLAIN PLAN SET QUERYNO = 1 FOR [your sql statement here];
This command will put the Explain information in the PLAN_TABLE.
Ex: EXPLAIN the access path for the below queries.
EXPLAIN PLAN SET QUERYNO = 1 FOR SELECT * FROM employee WHERE EMP_NO = 10001;
EXPLAIN PLAN SET QUERYNO = 2 FOR SELECT * FROM employee WHERE DEPT_NO = 300;

Step3: Execute select statement on PLAN_TABLE to obtain explain information that is written
in STEP2.
SELECT *
FROM PLAN_TABLE
WHERE
QUERYNO = 1 or 2
ORDER BY TIMESTAMP, QUERYNO, QBLOCKNO, PLANNO, MIXOPSEQ
WITH UR;
QUERYNO should be the same used in the explain command on Step 1.

Step4:
Look at these fields of PLAN_TABLE for important information to understand the access path.
PLANNO – Number of steps necessary to process the query indicated in QBLOCKNO;
METHOD – Indicate joins method used for the step (PLANNO);
ACCESTYPE – Method used to access the table;
MATCHCOLS – Number of index key used for index scan (when ACCESTYPE is I, IN,
M, MX);
ACCESSNAME – Name of the index used for index scan (when ACCESTYPE is I, IN, M, MX);
INDEXONLY – Indicates if the index alone is enough to carry out the step;
PREFETCH – Indicates if data pages can be read in advance by prefetch;

Step5:

61
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Analyze the results using the following tips:


Is data accessed through an index?
ACCESSTYPE:
I – Index
This is the best access after the one-fetch index. It uses the index to retrieve rows.
The number of index columns used for matching is represented in MATCHCOLS.
I1 – One-fetch index access
Is the best access possible as it requires retrieving only one row. However, it applies only to
statement with a MAX or MIN function.
N – Index scan with IN keyword in the predicate.
In the example: T(IC1, IC2, IC3, IC4).
Command: Select * from T where IC1 = 1 AND IC2 (in 1,2,3) AND IC3 > 0 and IC4 = 1.
MATCHCOLS will be 3 and ACCESSTYPE will be N. The IN-List scan will be performed as
three matching index scan: (IC=1, IC2=1, IC3>0), (IC=1, IC2=2, IC3>0) and (IC=1, IC2=3,
IC3>0). If parallelism is supported they will execute in parallel.
MX – Multiple index scan.
More than one index is used to access a table. It is an efficient access path when no single index
is efficient and a combination of index provides efficient access.
R – Table space scan.
This is the worst type of access as the entire table will be searched to process the query.

MATCHCOLS
The number of index columns matched on an index scan.
If it is 0 all index keys and RIDs are read.
If one of the matching predicates is a range there will be no more matching columns. Example for
the index on T(IC1, IC2, IC3, IC4) for the following command the IC3 predicate won’t be used:
Select * from T where IC1=1 and IC2 > 1 and IC3 = 1. The position of the columns in the index
is used to decide that IC3 won’t be used.

INDEXONLY
If the columns needed for a SQL statement can be found in the index DB2 will not access the
table. INDEXONLY performance is very high.

PREFETCH
Prefetching determines in advance if a set of data pages is about to be used and then reads the
entire set into a buffer with a single asynchronous I/O operation.
S – Sequential prefetch: data pages read in advance are accessed sequentially.
Table space scan always uses sequential prefetch.
L – List prefetch: one or more indexes are used to select the RIDs list in advance.
D – Dynamic prefetch: the pages to be accessed will be non sequential.
Blank – Prefetch not expected.

SORTs
They add an extra step to the accessed data.
METHOD=3 – These sorts are used for ORDER BY, GROUP BY, SELECT DISTINCT or
UNION.
SORTC_UNIQUE, SORTC_ORDERBY, SORTC_GROUP_BY – Indicates an extra sort for an
UNIQUE, ORDER BY and GROUP BY clause.

System Tables

62
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

SYSIBM.SYSTABLESPACE
It has tablespace information
Important columns
. NAME -- Name of the tablespace
. STATUS -- It is used to check the status of the tablespace.
A - Available
C - Partitioning index not been created
P - Check pending status
S - Check pending status but scope is less than entire tablespace
. PGSIZE -- It tells either 4K or 32K page size.
. NTABLES -- It tells number of tables craeted in the tablespace
. CREATEDBY -- It tells about creator user id.
. STATSTIME -- It tells about timestamp of the last runstats
. LOCKRULE -- It tells about row, page, table, tablespace lock
A - lock type any
L - Large object
P - Page lock
R - Row lock
S - Tablespace lock
T - Table lock
. SEGSIZE -- It tells about number of pages in each segment.
It is zero for Simple and partitioned tablespace.
. PARTITIONS -- It tells about number of partitions in partitioned tablespace.
It is zero for Simple and segmented tablespace.
. LOG -- Y/N -- It tells about the changes are to be logged or not.
It tells about copy pending status of the tablespace.

SYSIBM.SYSTABLES
It contains one row for each table/view/alias
. NAME -- Name of the table
. TYPE -- Type of the object
T - Table
V - View
X - Auxiliary Table
A - Alias
. CREATOR -- Creator of the object
. DBNAME -- Database name in which this object is created.
. TSNAME -- Tablespace name in which this object is created.
. PARENTS -- Number of parent tables for this table.
. CHILDREN -- Number of child tables on this table.
. STATUS -- Status of the table.
I - Incomplete
X - Table has unique constraint and table definition is complete.
Blank - Table has no unique constraint and table definition is complete.
. CHECKFLAG -- It says about the check constraints
C - Check pending either with referential constraint or table check constraint.
Blank - There are no referential or table check constraints on the table.

. STATSTIME -- Timestamp of the last runstats on this table.

63
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

. TBCREATOR -- It is for an alias and it says creator of the referred table.


. TBNAME -- It is for an alias and it says referred table of the alias.
. CREATEDTS -- Time when the create statement was executed.
. ALTEREDTS -- Time when the alter statement was executed.

SYSIBM.SYSCOLUMNS
It contains a row for every COLUMN of a table/view
. NAME -- Name of the column
. TBNAME -- Name of table on which this column is defined
. TBCREATOR -- Authorization Id of the owner of the table
. COLNO -- Column number of the column in the table
. COLTYPE -- Data type of the column
. LENGTH -- length of the column
. NULLS -- Null or not Null
Y - Null
N - Not Null
. UPDATES -- Whether column can be updated.
Y - Can be updated
N - It cannot be updated for the below reasons
.Column is derived from function or expression
.Column is ROWID data type
.A read only view
. CREATEDTS -- Timestamp when the column was created.
. ALTEREDTS -- Timestamp when the column was updated.
. HIDDEN -- Column can be hidden or not.
P - Partially hidden. This column is hidden from select *
N - not hidden

SYSIBM.SYSRELS
It contains a row for every foreign key of the table
. CREATOR -- Creator of the table that has referential constraint (Child table).
. TBNAME -- Name of the child table that has referential constraint.
. RELNAME -- Referential constraint
. REFTBNAME -- Name of the parent table
. REFTBCREATOR -- Authorization Id of the owner of the parent table
. COLCOUNT -- Number of columns in the foreign key
. DELETERULE -- Delete rule for the referential constraint
A - No action
C - Cascade
N - Set Null
R - Restrict
. TIMESTAMP -- Date and time when the referential constraint was created
. ENFORCED -- Referential integrity is enforced by the system or not
Y - Enforced by the system
N - Not enforced by the system
. CHECKEXISTINGDATA -- Option for checking existing data
I - Immediately check existing data
N - Never check existing data

SYSIBM.SYSINDEXES

64
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

It contains a row for every index of a table

. NAME -- Name of the index


. CREATOR -- Authorization ID of the owner of the index
. TBNAME -- Name of the table on which the index is defined
. TBCREATOR -- Authorization ID of the owner of the table
. UNIQUERULE -- whether index is unique
D - Duplicates are allowed
U - Unique
P - Unique and it is primary index
. CLUSTERRATIO -- Percentage of rows that are in the clustering order.
. STATSTIME -- Runstats time.
. INDEXTYPE -- Index type.
2 - Type 2 index
Blank - Type 1 index
D - Data partitioned secondary index

SYSIBM.SYSTABAUTH
It Records the privileges that users hold on tables and views

. GRANTOR -- Authorization id of the grantor


. GRANTEE -- Authorization id of the grantee/Application package/PUBLIC/PUBLIC*
. GRANTEETYPE -- Type of grantee
Blnak - An authorization id
P - An application plan or package. It is a package if COLLID is not blank
. TCREATOR -- Authorization id of the creator
. TTNAME -- Name of the table of view
. UPDATECOLS -- Update cols authorization
Blank - Authorization for all columns
* - Only for few columns. These columns can be seen in SYSIBM.SYSCOLAUTH
. ALTERAUTH -- Whether the GRANTEE can alter the table
Blank - Privilege is not held
G - Privilege is held with grant option
Y - Privilege is held without grant option
. DELETEAUTH -- Whether the GRANTEE can delete rrows from the table
Blank - Privilege is not held
G - Privilege is held with grant option
Y - Privilege is held without grant option
. INDEXAUTH -- Whether the GRANTEE can create indexes on the table
Blank - Privilege is not held
G - Privilege is held with grant option
Y - Privilege is held without grant option
. INSERTAUTH -- Whether the GRANTEE can insert rows into the table
Blank - Privilege is not held
G - Privilege is held with grant option
Y - Privilege is held without grant option

. SELECTAUTH -- Whether the GRANTEE can select rows the table or view

65
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Blank - Privilege is not held


G - Privilege is held with grant option
Y - Privilege is held without grant option
. UPDATEAUTH -- Whether the GRANTEE can update rows of the table or updatable view
Blank - Privilege is not held
G - Privilege is held with grant option
Y - Privilege is held without grant option
. REFERENCESAUTH -- Whether the GRANTEE can create or drop foreign keys on the
table
Blank - Privilege is not held
G - Privilege is held with grant option
Y - Privilege is held without grant option
. TRIGGERAUTH -- Whether the GRANTEE can create or drop foreign keys on the table
Blank - Privilege is not held
G - Privilege is held with grant option
Y - Privilege is held without grant option
. GRANTEDTS -- Time when the GRANT statement was executed

SYSIBM.SYSCHECKS
It contains a row for every check constraint
. TBOWNER -- Authorization id of the owner of the table
. CREATOR -- Authorization id of the creator of the check constraint
. TIMESTAMP -- Time when check constraint is created
. TBNAME -- Name of the table on which the check constraint is defined
. CHECKNAME -- Table check constraint name
. CHECKCONDITION -- Text of the table check constraint

SYSIBM.SYSPLAN
It contains one row for each application plan

. NAME -- Name of the application plan


. CREATOR -- Creator/owner of the application plan
. VALIDATE -- Object validation
B - Bind time
R - Run time
. ISOLATION -- How the tables are isolated from other applications
R - RR (Repeatable read)
T - RS (Read stability)
S - CS (Cursor stability)
U - UR (Uncommitted read)
. AQUIRE -- When resources are aquired
A - At allocation time
U - At first use
. RELEASE -- When resources are released
D - At deallocation time
C - Commit time

. EXPLAIN -- Explain option specified for the plan

66
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Y - Explain the path info into USERID.PLAN_TABLE


N - No explain
. QUALIFIER -- Qualifier used for the unqualified tables in static sql statements
. BOUNDTS -- Timestamp of last bind
. RELBOUND -- Release when the package was bound or rebound
Blank - Bound Prior to version 7
K - Bound prior on version 7
L - Bound prior on version 8
. BOUNDBY -- Authorization id of last bind

SYSIBM.SYSPACKAGE
It contains a row for every package

. COLLID -- Name of the package collection


. NAME -- Name of the package
. OWNER -- Authorization id of the package
. BINDTIME -- Last bind time
. QUALIFIER -- Same as SYSIBM.SYSPLAN
. VALIDATE -- Same as SYSIBM.SYSPLAN
. ISOLATION -- Same as SYSIBM.SYSPLAN
. RELEASE -- Same as SYSIBM.SYSPLAN
. EXPLAIN -- Same as SYSIBM.SYSPLAN
. QUOTE -- SQL string delimiter for the SQL statements in package
N - Apostrophes
Y - Quotation mark
. COMMA -- Decimal point representation
N - period
Y - Comma
. HOSTLANG -- Host language
B - Assembler
C - OS/VS COBOL
D - C language
F - Fortran
P - PL/I
2 - VS COBOLII or IBM COBOL release 1
3 - IBM COBOL release 2 or subsequent release
. VERSION -- Version Identifier
. RELBOUND -- Same as SYSIBM.SYSPLAN

SYSIBM.SYSDUMMY1
It is used to execute a sql statement where the table reference is required but data is not required.
To achieve the below operations without any user defined tables.
String manipulation
Get system dates
To achieve date conversions
To do Arithmetic operations

SYSIBM.SYSTRIGGER

67
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

It contains a row for each trigger


. NAME -- Name of the trigger
. CREATEDBY -- Authorization id of the creator of the trigger
. TBNAME -- Name of the table to which this trigger applies
. TBOWNER -- Qualifier of the name of the table to which this trigger applies
. TRIGTIME -- Time when triggered actions is applied
B - Trigger is applied before the event
A - Trigger is applied after the event
. TRIGEVENT -- Operation that activates the trigger
I - Insert
U - Update
D - Delete
. CREATEDTS -- Time when the trigger is created
. TEXT -- Trigger statement

Db2 Utilities

Unload- Load Utility

Sample Jcl:
//CDSUP3UL JOB (99247T),'unload and load',MSGCLASS=X,
// CLASS=A,REGION=8M,NOTIFY=&SYSUID
//*
//JOBLIB DD DSN=DSN710.TARGETA.SDSNLOAD,DISP=SHR
// DD DSN=DSN710.TARGETA.SDSNEXIT,DISP=SHR
// DD DSN=CEE.SCEERUN,DISP=SHR
//*
//STEP1 EXEC PGM=DSNUTILB,PARM=(DB2P,UTIL1)
//SYSPRINT DD SYSOUT=*
//SYSIN DD *
UNLOAD DATA FROM TABLE QUAL1.ACR HEADER NONE
WHEN (COMPANY_CODE = '001')
NOPAD SHRLEVEL REFERENCE
/*
//SYSREC DD DSN=TSO.DB2P.ACR,  Data extracted into this file
// DISP=(,CATLG,DELETE),
// UNIT=SYSALLDA,SPACE=(CYL,(10,5),RLSE),
// DCB=(RECFM=VB,BLKSIZE=0)
//SYSPUNCH DD DSN=TSO.DB2P.ACR.BCARDS,  Control information used for next
// DISP=(MOD,CATLG,DELETE), load is copied into this file
// UNIT=SYSALLDA,SPACE=(TRK,(1,1),RLSE),
// DCB=(RECFM=FB,BLKSIZE=0,LRECL=80)
//STEP2 EXEC PGM=DSNUTILB,PARM=(DB2T,UTIL1)
//SYSPRINT DD SYSOUT=*
//SYSIN DD DSN=TSO.DB2P.ACR.BCARDS,DISP=SHR  Control information
//* generated in unload
//SYSREC DD DSN=TSO.DB2P.ACR,DISP=SHR  Data file that is extracted
//* from unload

Control information that is stored into TSO.DB2P.ACR.BCARDS is shown below.

LOAD DATA INDD1 SYSREC LOG NO RESUME YES ENFORCE NO


EBCDIC CCSID(01140,00000,00000)
SORTKEYS 4686768
INTO TABLE QUAL1.ACR

( "COMPANY_CODE"
POSITION( 00001:00003) CHAR(00003)

68
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

, "AGENT_ID"
POSITION( 00004:00013) CHAR(00010)
.
.
.
, "SERVICE_DATE"
POSITION( 00314:00323) DATE EXTERNAL
)

Terminate Utility

If any utility is failed in its execution, then it has to be terminated before that table is
used for any operation.
Execute the below command from the option 7 (Commands) of DB2I (DB2 interactive). You can
see active utilities that are running and utilities that are failed.
-DIS UTIL(*)

Sample JCL:
//USER1AB JOB (99247T),'TERMINATE',MSGCLASS=X,CLASS=C
//*
//JOBLIB DD DSN=DSN710.TARGETA.SDSNLOAD,DISP=SHR
// DD DSN=DSN710.TARGETA.SDSNEXIT,DISP=SHR
// DD DSN=CEE.SCEERUN,DISP=SHR
//*
//JS10 EXEC PGM=IKJEFT01
//SYSTSPRT DD SYSOUT=*
//SYSPRINT DD SYSOUT=*
//SYSUDUMP DD SYSOUT=*
//SYSTSIN DD *
DSN SYSTEM(DB2T)
-TERM UTILITY(UTIL1)
//*

Repair utility

Sample jcl:
//USERABL JOB (99247T),'Repair jcl',MSGCLASS=X,
// CLASS=C,REGION=8M,NOTIFY=&SYSUID
//*
//JOBLIB DD DSN=DSN710.TARGETA.SDSNEXIT,DISP=SHR
// DD DSN=DSN710.TARGETA.SDSNLOAD,DISP=SHR
//*
//STEP1 EXEC PGM=DSNUTILB,PARM='DB2T,REPAIR1'
//SYSPRINT DD SYSOUT=*
//SORTWK01 DD DSN=&&TEMP01,DISP=(NEW,DELETE,DELETE),
// SPACE=(16384,(20,20),,,ROUND),UNIT=SYSDA
//SYSREC DD DSN=&&SYSREC,DISP=(NEW,DELETE,DELETE),
// SPACE=(16384,(20,20),,,ROUND),UNIT=SYSDA
//SYSUT1 DD DSN=&&SYSUT1,DISP=(NEW,DELETE,DELETE),
// SPACE=(16384,(20,20),,,ROUND),UNIT=SYSDA

//SORTOUT DD DSN=&&SORTOUT,DISP=(NEW,DELETE,DELETE),
// SPACE=(16384,(20,20),,,ROUND),UNIT=SYSDA
//SYSIN DD *
REPAIR SET TABLESPACE dbname.tsname NOCHECKPEND/NOCOPYPEND
/*

Reorg utility

69
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Reorg command in DSNUTILB is recommended after the reorg recommended alter statement.
Otherwise the table cannot be used for any SQL operations.

Sample JCL:
//USER1AB JOB (99247T),'REORG',MSGCLASS=X,CLASS=C
//*
//JOBLIB DD DSN=DSN710.TARGETA.SDSNLOAD,DISP=SHR
// DD DSN=DSN710.TARGETA.SDSNEXIT,DISP=SHR
// DD DSN=CEE.SCEERUN,DISP=SHR
//*
//RUNST1 EXEC PGM=DSNUTILB,PARM=(DB2T,UTIL1)
//*
//SYSPRINT DD SYSOUT=*
//UTPRINT DD SYSOUT=*
//SYSIN DD *
REORG TABLE table_owner.table_name
/*

Runstats Utility

It is recommended to run the RUNSTATS command:


1. After large number of updates
2. After significant inserts/deletes have been made
3. After tables have been reorganized
4. After new indexes have been created
5. Before binding programs whose performance critical

Sample Jcl:
//TABCSPL1 JOB (99247M),'PPLUS SPECIAL JOB 0',MSGCLASS=X,CLASS=C
//*
//JOBLIB DD DSN=DSN710.TARGETA.SDSNLOAD,DISP=SHR
// DD DSN=DSN710.TARGETA.SDSNEXIT,DISP=SHR
// DD DSN=CEE.SCEERUN,DISP=SHR
//*
//RUNST1 EXEC PGM=DSNUTILB,PARM=(DB2T,UTIL1)
//*
//SYSPRINT DD SYSOUT=*
//UTPRINT DD SYSOUT=*
//SYSIN DD *
RUNSTATS TABLESPACE ( QUAL1.TSACR ) TABLE( QUAL1.ACR )
INDEX(ALL) UPDATE (ALL) HISTORY (ALL)
/*

Tables that are updated with UPDATE and HISTORY options


SYSTABLESPACE
SYSTABLEPART1
SYSTABLEPART_HIST1
SYSTABLES1
SYSTABLES_HIST1
SYSTABSTATS1,2
SYSTABSTATS_HIST1,2
SYSLOBSTATS3
SYSLOBSTATS_HIST3

INTEGRITY

70
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

Integrity consists of a set of rules used in DB2 to provide accuracy, validity or correctness of data
in database. Maintaining integrity is not an easy task in a multi user environment. So the task of
maintaining integrity is handled by the system than the user.
There are two general integrity rules in db2 for maintaining data integrity.

Entity integrity:
DB2 supports Entity integrity rule by enforcing the programmer to make the column declaration
of the primary key not null. If the primary key is composite then all the columns in that composite
key should be declared as not null.

Referential integrity:
It ensures the data integrity between the tables related by primary(parent) and foreign(child) keys.
INSERT rule
The insert rule is automatic and not explicitly specifiable on the foreign key declaration.
The rule states that Any row inserted into a dependent table must have its foreign key value as
either a NULL or, equal to the value of a primary key in the parent table that it references.

DELETE rule
This rule is explicitly specified for each foreign key in a table. The DELETE rule states the
requirements to be met when a row in a parent table is deleted. Each foreign key is associated
with its own DELETE rule. All applicable DELETE rules are used to determine whether or not a
delete is done.

RESTRICT option A row of a parent table cannot be deleted if rows exist in the dependent
table(s) with foreign key values equal to the primary key value of this row.

CASCADE option If a row of a parent table is deleted, then: all rows in the dependent table(s)
with foreign key values equal to the primary key value of this row will also be deleted. The delete
will also impact the dependents of the dependent table(s).

SET NULL option If a row of a parent table is deleted then all rows in the dependent table with a
foreign key value equal to the primary key value of this row will have its foreign key value
changed to NULL.

UPDATE rule
The UPDATE rule is automatic and not explicitly specifiable on a foreign key declaration.
This rule states the requirements to be met when the foreign key value of a row in a dependent
table is updated. It can be updated to a value that is NULL or to the value of a primary key in the
parent table that it references. ... primary key value of a row in a parent table is updated. The
primary key value of a row of a parent table cannot be updated if rows in the dependent table(s)
exist with foreign key values equal to the primary key value of this row.

Concurrency

71
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

DB2 is a shared system, that is a system that allows any number of users to access the same
database at the same time. Any such system requires some kind of concurrency control
mechanism to ensure that concurrent transactions do not interfere with each other operation. The
absence of such a mechanism will lead to errors and inconsistencies in data

DB2 uses locks to control access to same database by multiple users. The basic idea of locking is
simple, when a transaction needs an assurance that some object that is interested in, will not
change in some unpredictable manner by another user. An exclusive lock on the object will
provide this assurance. The effect of the lock is to lock other transactions out of the object, and
thereby to prevent them from changing it. The first transaction is thus able to carry out its
processing in the certain knowledge that the object in question will remain in a stable state for as
long as the transaction wishes to.

If a transaction requests a lock that is not currently available, then the transaction simply waits
until it gets it. In practice the installation can specify a maximum wait time; If a transaction ever
reaches that threshold in waiting for a lock, it times out and the lock request is failed.

Locking Strategy
DB2 allows multiple users to access same object at same time, but they are controlled by locks.
DB2 selects appropriate locking mechanism based on concurrency control requirements inherent
in the application program. They are called implicit locks.
In addition to the implicit locking mechanism, DB2 provides certain explicit facilities.

These explicit facilities are


LOCKSIZE parameter of CREATE TABLESPACE statement.
ISOLATION parameter
ACQUIRE / RELEASE parameter
SQL statement LOCKTABLE.

Lock table statement can be coded in the application program to acquire an explicit lock on an
object on behalf of the application program. Other parameters are explained in the following
pages.
Example
LOCK TABLE SP IN EXCLUSIVE MODE;

LOCK SIZES AND TYPES


The size (scope) of a lock on data in a table describes the amount of data controlled.
The size is specified in the locksize parameter of create tablespace statement.
Locksize Tablespace:
This means that all locks acquired on data in the tablespace will be at the table space level.
Locksize Table:
This means that locks acquired on data in the table space will be at the table level.
Locksize Page:
This means that locks acquired on data in the table space will be at the table level.
Locksize Row:
This means that locks acquired on data in the table space will be at the row level.
Locksize Any:
This means that db2 will decide the appropriate physical unit of locking for the tablespace.

Db2 always requires a Table or Tablespace lock before access to data is permitted.
Db2 may use Table or Tablespace lock alone to access data according to the locksize parameter.

72
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

If the locking strategy includes Row or Page locking then db2 locks Table or Tablespace before
locking Row or Page.

Modes of Table and Tablespace Locks

IS (Intent Share): The lock owner can read any data in the table if an ‘S’ lock can be obtained
on the target row or page.

IX (Intent Exclusive): The lock owner can read or change any data in the table provided an
‘X’ lock can be obtained on rows or pages to be changed and a ‘U’ or ‘S’ lock can be obtained on
rows to be read.

SIX (Share with Exclusive) : The lock owner can read any data in the table and change rows in
the table provides it can be obtain an ‘X’ lock on the target row or page for change .Row locks
are not obtained for reading.

S (Share): The lock owner can read any data in the table and will not obtain roe or table locks.

U (Update): The lock owner can read any data in the table and may changed data if an ‘X’ lock
on the table can be obtained .No row or page locks are obtained.
X (Exclusive): The lock owner can read or update any data in the table .Row locks are not
obtained.

Modes of Row and Page Locking

S (Share): The row is being read by only one application and is available for read only by other
applications.

U (Update): The row is being read by one application but is possibly to be changed by that
application. The row is available for read only by other applications.

X (Exclusive): The row is being changed by one application and is not available for other
application.
Row level locks are only requested by applications that have supporting locks at the table level.

SQL CODES

73
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2

-007 SQL statement contains illegal char


-029 An into class is required
-060 The specified data type has invalid length
-101 The SQL Statement exceeds an established DB2 limit.
too many tables or too many bytes in the statement
-118 Table or view is illegally named in both the data modification and from clause

-180 Syntax for string representation of a date or time is invalid


-181 String representation of date or time value is invalid
-182 The date or time value in an arithmetic expression is invaid
-183 the result of the arithmetic expression returns a date or time value i.e. not in
the range of values

-204 The object name is undefined


-206 The column name not found in a table given in from clause

-301 The host variable data type is invalid


-305 Null indicator variable is missing and the field returns null value

-501 A cursor must be opened before attempting to fetch from it or close it


-502 Trying to open a cursor which is already opened
-509 You cannot update from a different table than the one specified on the cursor
referred by the where current of clause
-530 Invalid foreign key value was specified for the constraint name
-531 A primary key value cannot be updated if foreign key currently exists that
reference that value
-532 The deletion violates the named referential constraint
-551 The user is attempting to perform an operation on the specified object for
which the user is not authorized or the table does not exist

-803 Primary key violation. Insert or update


-805 Program not found in the plan
-811 A cursor is not defined but the SQL is returning more than one row
-818 Timestamp mismatch

-904 The specified resource is unavailable


-911 The current unit of work has been rolled back
-913 The execution is unsuccessful due to a deadlock or time out
-922 A connection authorization failure an attempt was made to access DB2 from
TSO, CICS. So the connection attachment facility is inactive
-923 A connection was not established because the DB2 was unavailable

74

You might also like