Professional Documents
Culture Documents
Wa0003
Wa0003
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.
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
3
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2
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.
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
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
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
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
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
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)
/*
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
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 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.
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 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 |
-------------- --------------
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
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;
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';
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
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.
10
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2
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 .
11
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2
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.
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.
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.
Data type depends on the nature of the data itself and will always be one of two types NUMERIC
or CHARACTER .
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 .
13
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2
14
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2
A powerful database management language that performs the function of data manipulation, data
definition and data control and a non-procedural language.
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]
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.
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.
17
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2
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;
Example:
CREATE VIEW EMP_VIEW
AS SELECT EMPNO,NAME,DEPT,JOB FROM EMPLOYEE.
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);
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.
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
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.
20
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2
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
21
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2
IN DBNAME.TSNAME;
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;
+------------------------------------------------------------------+
¦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
+------------------------------------------------------------------+
DEPARTMENT TABLE
+-------------------------------+
¦DEPTNO¦ DEPTNAME ¦ MANAGER¦
+------+---------------+--------¦
¦ 100 ¦ PRODUCTION ¦ 737466 ¦
¦ 200 ¦ ACCOUNTING ¦ 865403 ¦
¦ 300 ¦ PERSONNEL ¦ 491640 ¦
¦ 400 ¦ ENGINEERING ¦ 604985 ¦
+-------------------------------+
INSERT format1:
It assigns values to columns in the order the columns appear in the table.
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¦
+-------------------------------------------------+
25
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2
¦ 100 ¦ ------+
+------+
+------------------------+
¦ 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.
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.
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¦
+------------------------------------------------------------------------+
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
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.
+-------------------------------+
¦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¦
+-------------------------------+
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 <=.
+------------------------+
¦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.
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.
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.
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
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.
Ex: To find the average salary of all employees from the EMPLOYEE table.
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
SQL only counts each different value once. There are 4 unique values.
DEPTNO
100 <----
500 <----
300 <----
100
300
100
200 <----
500
100
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.
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.
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.
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 .
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
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
36
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2
JOINS
SELECT * FROM PARTS;
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
37
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2
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
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
39
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2
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;
EX: DELETE
FROM EMPLOYEE
WHERE EMPNO = 737654;
EMBEDDED SQL
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.
40
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2
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.
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.
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'.
42
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2
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
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
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).
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
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
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
OPEN cur1
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
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.
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.
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)
+-------------+
48
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2
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
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.
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
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.
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.
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
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.
54
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2
Dynamic Sql
01 WS-STMT.
05 WS-STMT-LEN PIC S9(04) COMP.
05 WS-STMT-TEXT PIC X(50).
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.
Declare Cursor
EXEC SQL
DECLARE C1 CURSOR FOR 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)
DELETE grants the privilege to delete rows from the table or updatable view
. Ability to delete rows from table and updatable views
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
57
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2
Examples:
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
Revoke
ALTER
CONTROL
DELETE
INDEX
INSERT
REFERENCES
SELECT
UPDATE (COLUMN)
Examples:
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.
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.
59
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2
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%'
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.
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
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.
63
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2
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
SYSIBM.SYSTABAUTH
It Records the privileges that users hold on tables and views
. SELECTAUTH -- Whether the GRANTEE can select rows the table or view
65
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2
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
66
School of MAINFRAMES
Ph : 040-64515137 Email: schoolofmainframes@gmail.com DB2
SYSIBM.SYSPACKAGE
It contains a row for every package
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
Db2 Utilities
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
( "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
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)
/*
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.
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;
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.
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.
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
74