Вы находитесь на странице: 1из 73

DB2

Version: DB2/HANDOUT/0804/1.0 Date: 04-08-04

Cognizant Technology Solutions 500 Glen Pointe Center West Teaneck, NJ 07666 Ph: 201-801-0233 www.cognizant.com Copyright 2004, Cognizant Academy, All Rights Reserved

DB2

TABLE OF CONTENTS

Introduction ........................................................................................................................6 About this Module ...............................................................................................................6 Target Audience .................................................................................................................6 Module Objectives ..............................................................................................................6 Pre-requisite.......................................................................................................................6 Chapter 1: Introduction to DB2 .............................................................................................7 Learning Objectives ............................................................................................................7 Data and Databases ...........................................................................................................7 Different Database Systems ................................................................................................7 Types of Database Systems ................................................................................................7 Advantages of Database Systems........................................................................................8 RDBMS Concepts...............................................................................................................8 Normalization .....................................................................................................................9 Types of Integrity .............................................................................................................. 10 Relational Example ........................................................................................................... 10 Test your Understanding ................................................................................................... 11 Chapter 2: DB2 Objects and Data types.............................................................................. 12 Learning Objectives .......................................................................................................... 12 DB2 Internal Structure ....................................................................................................... 12 System Services ............................................................................................................... 12 Locking Services ............................................................................................................... 12 Database Services ............................................................................................................ 12 Distributed Data Facility..................................................................................................... 13 DB2 Objects ..................................................................................................................... 13 Using Storage Group-Features .......................................................................................... 13 Using User Defined VSAM datasets ................................................................................... 14 Buffer pool........................................................................................................................ 14 DATABASE ...................................................................................................................... 14 TABLESPACE .................................................................................................................. 15 Segmented Table space.................................................................................................... 16 Tablespace Parameters .................................................................................................... 17 Copyright 2004, Cognizant Academy, All Rights Reserved

DB2
TABLES-Features ............................................................................................................. 19 Special Registers: ............................................................................................................. 19 Types of Constraints: ........................................................................................................ 21 INDEX.............................................................................................................................. 22 INDEXSPACE .................................................................................................................. 25 VIEWS ............................................................................................................................. 25 SYNONYMS-What is it?.................................................................................................... 26 DB2 Data types................................................................................................................. 27 Test your Understanding ................................................................................................... 28 Chapter 3: SQL ................................................................................................................... 29 Learning Objectives .......................................................................................................... 29 Introduction to SQL ........................................................................................................... 29 QMF (Query Management Facility)..................................................................................... 30 SPUFI .............................................................................................................................. 30 Types of SQL ................................................................................................................... 30 Definition Language (DDL) ................................................................................................ 31 General Rules for Referential Integrity and Table Parameters .............................................. 31 Data Manipulation Language ............................................................................................. 32 Comparison Operators ...................................................................................................... 33 Some Rules for Column Functions: .................................................................................... 35 Some Rules for Scalar Functions: ...................................................................................... 37 Arithmetic Functions .......................................................................................................... 37 Duplicates ........................................................................................................................ 37 Sorting Records ................................................................................................................ 37 Rules for Order By: ........................................................................................................... 38 Grouping Records ............................................................................................................. 38 Rules for Group By:........................................................................................................... 38 Complex SQLs................................................................................................................. 39 Joins ................................................................................................................................ 39 Types of Joins .................................................................................................................. 40 INNER JOIN (Default): ...................................................................................................... 40 Union ............................................................................................................................... 44 Data Control Language ..................................................................................................... 45 Copyright 2004, Cognizant Academy, All Rights Reserved

DB2
Grant................................................................................................................................ 45 Revoke............................................................................................................................. 45 Test your Understanding ................................................................................................... 46 Chapter 4: DB2 Application Programming.......................................................................... 47 Learning Objectives .......................................................................................................... 47 About Static SQL .............................................................................................................. 47 About Dynamic SQL.......................................................................................................... 47 Embedded SQL ................................................................................................................ 47 Steps Involved in Application Programming ........................................................................ 49 Coding the application ....................................................................................................... 50 Host Structures ................................................................................................................. 50 Embedded SQL ................................................................................................................ 50 DCLGEN.......................................................................................................................... 51 SQLCA (SQL Communication Area)................................................................................... 52 Null-Indicator Variables ..................................................................................................... 53 Cursors ............................................................................................................................ 54 Update/Delete using Cursor............................................................................................... 55 Commit ............................................................................................................................ 56 When is a commit issued: -................................................................................................ 56 Checkpoint-Restart Logic:.................................................................................................. 57 Pre-compilation................................................................................................................. 57 Compilation and Link ......................................................................................................... 58 Bind ................................................................................................................................. 58 What is Collection? ........................................................................................................... 60 Bind Parameters ............................................................................................................... 61 Execution ......................................................................................................................... 62 Application Programming Guidelines .................................................................................. 65 Chapter 5:DB2 Utiliti e s ....................................................................................................... 66 Learning Objectives .......................................................................................................... 66 Data Consistency Utilities .................................................................................................. 66 REPAIR Utility .................................................................................................................. 66 REPORT Utility................................................................................................................. 66 COPY Utility ..................................................................................................................... 66 Copyright 2004, Cognizant Academy, All Rights Reserved

DB2
MERGECOPY Utility ......................................................................................................... 66 QUIESCE Utility................................................................................................................ 67 RECOVER Utility .............................................................................................................. 67 REORG Job Streams ........................................................................................................ 68 EXPLAIN .......................................................................................................................... 68 DB2 Security, Catalog Tables and Optimizer ...................................................................... 68 Performance Tuning.......................................................................................................... 71 REFERENCES ..................................................................................................................... 72 WEBSITES....................................................................................................................... 72 BOOKS ............................................................................................................................ 72 STUDENT NOTES: .............................................................................................................. 73

Copyright 2004, Cognizant Academy, All Rights Reserved

DB2

Introduction
About this Module
This module deals with the fundamentals of DB2

Target Audience
This module is specifically aimed at Entry Level Trainee Programmers

Module Objectives
The main objectives of the module are:
?? An introduction to:

o o o o o

Relational Database Management Concepts Different DB2 objects and data types. Structured Query Language Application Programming, Compilation and Execution of DB2 programs Different DB2 utilities

Pre-requisite
To follow the course successfully, a student needs to have a prior knowledge of the following:
?? TSO/ISPF ?? MVS ?? COBOL programming

Copyright 2004, Cognizant Academy, All Rights Reserved

DB2

Chapter 1: Introduction to DB2


Learning Objectives
The chapter shall achieve the following objectives:
?? An Understanding of different Database systems ?? Understanding the Advantages of Databases over conventional file systems ?? Understanding RDBMS concepts

Data and Databases


What is Data? A representation of facts or instruction in a form suitable for communication What is Database? A repository for stored data

Different Database Systems


A database system is an integrated and shared repository for stored data or collection of stored operational data used by application systems of some particular enterprise. Or Nothing more than a computer-based record keeping system.

Types of Database Systems


Hierarchical
?? This kind of database system can be visualized as an upside-down tree of data ?? A single table acts as the "root" (Parent) of the database from which other tables

"branch(Children) out
?? Child may only have one parent but a parent can have multiple children ?? This child/parent rule assures that data is systematically accessible. ?? Redundancy

would occur because hierarchical databases handle one-to-many relationships well but do not handle many-to-many relationships well.

Network
?? The network model uses set theory to provide architecture. ?? Child tables are allowed to have more than one parent ?? Network model supports many-to-many relationships ?? The

Network model solves the problem of data redundancy by representing relationships in terms of sets rather than hierarchy

?? The model was difficult to implement and maintain.

Copyright 2004, Cognizant Academy, All Rights Reserved

DB2
Relational
?? The concept of a table in which all data is stored ?? The database is represented in terms of Entities, Relations and Attributes. ?? Database is a collection of tables, constraints

Advantages of Database Systems


Advantages over File Management System are:
?? Data redundancy ?? Multiple views ?? Shared data ?? Data independence (logical/physical) ?? Data dictionary ?? Search versatility ?? Cost effective ?? Security & Control ?? Recovery restart & Backup ?? Concurrency

RDBMS Concepts
Relational Properties Relation is a mathematical term for a table - Hence Relational database is perceived by the users as a set of tables. The main characteristics of relation are:
?? All data values are atomic. ?? Entries in columns are from the same domain ?? Sequence of rows (Top to Bottom) is insignificant ?? Each row is unique ?? Sequence of columns (Left to Right) is insignificant

Relational Terminology Relation: Tuple: Attributes: Domain: -A table or File -Row contains an entry for each attribute -Columns or the characteristics that define the entity -A range of values (or Pool)

Entity: -Some object about which we wish to store information Null: Atomic: -Represents an unknown 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). This exists only for a short period of time and the primary and attribute key Copyright 2004, Cognizant Academy, All Rights Reserved

DB2
take its place. Primary key: row. Alternate key: Foreign key: -The candidate key that is chosen for primary attributes to uniquely identify each -The remaining candidate keys that were not chosen as primary key -An attribute of one relation that might be a primary key of another relation.

Entity Relationship Model: Features


?? E-R model is a logical representation of data for a business area ?? Represented

as entities, relationship between entities and attributes of both relationships and entities expressed in the form of an E-R diagram

?? E-R models are outputs of analysis phase i.e. they are conceptual data models

Normalization
Normalization is done to bring the design of database to a standardized mode
?? 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 non-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

Copyright 2004, Cognizant Academy, All Rights Reserved

DB2 Types of Integrity


?? Entity Integrity: Rule states that no column that is part of a primary key can have a

null value
?? Referential Integrity: Rule states that every foreign key in the first table must either

match a primary key value in the second table or must be wholly NULL.
?? Domain Integrity: Integrity of information allowed in column

Relational Example

CUSTOMER Places ORDERS ORDERS Has PRODUCTS

The above example can be interpreted as follows:


?? A Customer can place any number of orders (one-to-many) ?? Each order relates to only one customer (one-to-one) ?? One order can contain many products (one-to-many) ?? One Product can be a part of many orders (one-to-many) ?? In the above example Customer, Order & Product are called ENTITIES. ?? An Entity may transform into table(s). ?? The unique identity for information stored in an ENTITY is called a PRIMARY KEY.

E.g. Customer-No uniquely identifies each customer A table essentially consists of


?? Attributes, which define the characteristics of the table ?? Primary key, which uniquely identifies each row of data stored in a table ?? Secondary & Foreign Keys/indexes

Hence the Table Definition will be: Table Customer Attributes - Customer-No, Cust-name, Cust-location, Cust-Id, Order-no... Primary Key Foreign-Key - Customer-No - Order-no Secondary Key - Cust-Id

The Relationships transform into Foreign Keys. For e.g. Customer is related to Orders thru Order-No, which is the Foreign-key in Customer and Primary key in Order. So basically the relationship Places is thru the Order-No. Copyright 2004, Cognizant Academy, All Rights Reserved

10

DB2
As per the relational integrity the Primary-Key, Order-No, for the table Orders can never be Null, while it can be so in the table Customer.

Test your Understanding


1). Characteristics of a Relational Database A. It supports many to many relationships B. Child Tables were allowed to have more than one parent C. Represented in terms of Entities and attributes D. A single table acts as a root

2). Column used to uniquely identify a Tuple A. Composite Key B. Alternate Key C. Primary Key D. Foreign Key

Answer: 1). C. 2). C

Copyright 2004, Cognizant Academy, All Rights Reserved

11

DB2

Chapter 2: DB2 Objects and Data types


Learning Objectives
The chapter shall achieve the following objectives:
?? An Understanding of the internal structure of DB2 system ?? An understanding of Different DB2 objects ?? An understanding of DB2 data types

DB2 Internal Structure


The Four major components of the complex DB2 internal structure are:
?? System Services ?? Locking Services ?? Database Services ?? Distributed data facility

System Services
?? Controlling connections to other MVS subsystems like CICS, IMS/DC, TSO ?? Handles system start-up, shutdown and operator communication. ?? Managing the system log, which records the information necessary for recovering

user and system data in case of system failure. When the active log dataset becomes full the system shifts to a new dataset and copies the old data to archive log. Information regarding the log datasets is recorded on a system dataset called the Bootstrap dataset.

Locking Services
?? Provides necessary controls for managing concurrent access to data using the IRLM. ?? IRLM-IMS resource lock manager. It is an MVS subsystem and a general-purpose

lock manager that aids in maintaining data integrity.

Database Services
Supports the definition, retrieval and update of DB2 data using a series of six sub components
?? Pre Compiler: -

This is a pre-processor for host programming language. Produces a DBRM.


?? Bind

Bind a given DBRM to produce what is known as Plan. Bind has two main functions syntax checking and optimization.
?? Runtime Supervisor

When the program executes first time the control goes to the runtime supervisor. It oversees execution and makes requests to the Data Manager. Copyright 2004, Cognizant Academy, All Rights Reserved

12

DB2
?? Database Manager

Does all the operations such as the search, retrieval, update index, maintenance etc. It also manages the physical databases. It invokes the system components as necessary in order to perform detailed functions such as locking, logging, I/O operations etc.
?? Buffer Manager

This is the component responsible for the physical transfer of data between external storage and virtual memory. It uses techniques such as read-ahead buffering and look-aside buffering to get the best performance of the buffer pools and to minimize the amount of physical I/O required.
?? Utilities

The database services component also maintains certain control and descriptor information regarding the database tables and their columns, database backup operations. This information is divided into two groups, which is namely catalog and the directory. The catalog consists of regular tables and is accessible by means of SQL statements. The directory cannot be accessed by SQL statements and it is for the internal use of the DB2. Both contain the same information.

Distributed Data Facility


?? Distributed DB2 requests are carried out through DDF ?? Enables database access by remote systems

DB2 Objects
STORAGE GROUP For DB2 Datasets, we have 2 options for storage allocation
?? Storage Group ?? User-Defined Vsam

The option is defined as a part of Tablespace definition

Using Storage Group-Features


?? STOGROUP is a collection of direct access volumes, all of the same device type ?? Dataset allocation is performed by DB2 through IBMs Data Facility Product (DFP) ?? Max no of volumes per Stogroup is 133 (Ideally 3 or 4) and all volumes must be of

same type 3380, 3390, etc.


?? CREATE STOGROUP TESTSG1 ?? VOLUMES (VOL1, VOL2). ?? Default STOGROUP is SYSDEFLT. It is created when DB2 is installed. This should

be avoided.
?? The underlying VSAM datasets are created and maintained by DB2. ?? When a given space needs to be extended, storage is acquired from the appropriate

stogroup. Copyright 2004, Cognizant Academy, All Rights Reserved

13

DB2 Using User Defined VSAM datasets


?? 2 types of VSAM datasets can be used to represent DB2 Tablespaces and

Indexspaces - ESDS AND LDS


?? These are not used as plain VSAM datasets but DB2 uses VSAM Media Manager to

access them. Also DB2 does additional formatting of the datasets because of which they cannot be treated like Standard Vsam.
?? DB2 can use LDS more efficiently as it has a 4k CI size and has no control

information like ESDS.


?? DEFINE CLUSTER

(NAME (vcat.dsndbc.ddddddd.ssssssss.I0001.Annn) LINEAR REUSE VOLUMES (vol1, vol2) CYLINDER (pri sec) SHAREOPTIONS (3 3) )DATA (NAME(vcat.dsndbd.ddddddd.ssssssss.I0001.Annn)) vcat represents an ICF catalog

Buffer pool
BUFFERPOOL is buffer area used to maintain recently accessed table and index pages. Data is first read from a table, which is in a VSAM dataset and is moved into a BUFFERPOOL and from there it is sent to the requester. There are totally 60 BUFFERPOOL options 50 4K BUFFERPOOLS (BP0 thru BP49) and 10 32K BUFFERPOOLS BP32K thru BP32K9.

DATABASE
The total collection of stored data is divided into a number of user databases and a few system databases .
?? Database is a group of logically related Tablespaces and Indexspaces, which in turn

contain tables and indexes respectively.


?? It is the unit of START and STOP for the system administrator. ?? Default Database is DSNDB04, which is created during installation. ?? The parameters used for the creation are

o o

STOGROUP

- Default is SYSDEFLT

BUFFER POOL - Default is BP0

?? A STOGROUP & BUFFERPOOL must be defined for each database. ?? A database may occupy more than one disk space ?? In a given database, all the spaces need not have the same stogroup

Copyright 2004, Cognizant Academy, All Rights Reserved

14

DB2
?? More than one volume can be defined in a stogroup. DB2 keeps track of which

volume was defined first & uses that volume.


?? DBD is Database Descriptor It is a control structure used by DB2 to manage the

objects, which are under the control of a given database.


?? Whenever any DB2 object in a database is created, altered or dropped, the DBD is

modified.
?? The DBD contains a mapping of the Tablespaces, tables and indexes defined in a

database.
?? An X lock is acquired on a DBD during the execution of the DDL. So it is better to

execute DDL when there is little or no activity.

CREATE DATABASE DATPRPDB STOGROUP D3DPSMS BUFFERPOOL BP3 INDEXBP BP4 CCSID EBCDIC;

TABLESPACE
?? Table space is a logical address space on secondary storage to hold one or more

tables
?? Table space contains one or more tables. Index space contains exactly one index. A

table and all of its indexes will be contained within a single database.
?? It is a dynamically extended collection of pages. Page is a block of physical storage

and it is the unit of I/O. The pages are all of 4K size for index spaces and 32K or 4K for table spaces.
?? Table space is the unit of recovery and reorganization.

There are 3 types of table spaces: Simple Table space


?? A Simple Table space can contain one or more tables. If there is more than 1 table,

a single page can contain records from more than one table.
?? For certain applications, storing more than one Table might enable faster retrieval for

joins using these tables. Usually only 1 table per Tablespace is preferred.
?? LOAD Utility for any one table in the TS with Replace option will delete all data in the

Tablespace.
?? Disadvantages Affects Concurrent access, data availability, space management.

Partitioned Table space


?? This type of Tablespace can contain exactly one table, which is so huge that it cannot

be maintained as a single unit.

Copyright 2004, Cognizant Academy, All Rights Reserved

15

DB2
?? So it is partitioned based on the value ranges of one or more columns in a table. For

this column or its combination, a clustering index must be defined. The key can have a maximum length of 40 bytes. Columns in a partitioning index cannot be updated.
?? There can be 1 to 64 partitions/TS ?? Each partition is independent of one another. Individual partitions can be associated

with different storage groups.


?? Individual partitions can be independently recovered and reorganized.

Advantages of a Partitioned Table space:


?? Allows us to isolate specific data areas in dedicated datasets. ?? Improves data availability ?? Improves recoverability ?? Encourages parallelism (Query Parallelism is breaking the data access for a query

into multiple I/O streams that is execute in parallel and which is useful in reducing the overall elapsed time)
?? For partitioned table space, individual partitions can be reorganized or recovered

Parameters for Partitioned TS are


?? NUMPARTS no of partitions ?? LARGE is used to allocate as much as 1TB of data in a Tablespace and

No of partitions can be max 254. If not, maximum storage amount is 64 GB and maximum number of partitions is 64.

Segmented Table space


?? A Segmented Table space can contain one or more tables. The table space is

divided into segments and the tables are stored in different segments.
?? A segment consists of a logically contiguous set of n pages ?? A segment can contain records of only one table. ?? 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

reorganization

Advantages over Simple TS:


?? Concurrent access is possible as data is in different segments ?? Handles free space more efficiently. ?? Mass delete is more efficient as data is deleted using the space map and without

reading it (unlike simple TS)


?? Space can be reclaimed from dropped tables immediately.

Copyright 2004, Cognizant Academy, All Rights Reserved

16

DB2

Parameters for Segmented TS are


?? SEGSIZE denotes the number of pages assigned to a segment

Tablespace Parameters
LOCKSIZE Denotes the type of locking for a particular Tablespace. Options are:
?? TABLESPACE Used when Shared access to multiple users is not required or when

the data is Read-Only


?? TABLE Applicable only for Segmented TS and when Shared access is not required ?? PAGE - To facilitate shared access (i.e. concurrency) ?? ROW

- To facilitate shared access to data, which could be on the same page. Used only when Page Locks werent sufficient for concurrent access.

?? ANY Means Let DB2 decide for each case, starting from Page Lock

LOCKMAX This is the maximum number of Row or Page level Lock for any one user in a Tablespace. If this value is reached, the lock gets escalated to table or Tablespace lock. Values can be
?? ??

0 ? lock escalation should never occur SYSTEM ? defaults to the system-wide value specified in DSNZPARMS Integer from 1 to 2,147,483,647

PCTFREE Denotes what % of each page should remain free for future inserts FREEPAGE Denotes the number of pages after which an empty page is available. The above 2 parameters are useful in reducing the frequency of reorganization, reducing contention and increasing the efficiency of insertion MAXROWS This indicates the maximum number of rows on a Tablespace page. Default is 255. CLOSE Possible values are Yes/No. It determines whether the underlying VSAM datasets should be closed after each time the table is used. Maximum number of datasets that can be open in DB2 at a time is 10,000 ERASE Possible values are Yes/No. This determines whether physical DASD where the TS resides has to be written with binary zeros when the TS is dropped. NUMPARTS - For Partitioned Tablespaces SEGSIZE - For Segmented Tablespaces

CREATE TABLESPACE ACTSACCT IN STEVDB01 NUMPARTS 32 (PART 1 USING STOGROUP STEVESG PRIQTY 252 Copyright 2004, Cognizant Academy, All Rights Reserved

17

DB2
SECQTY 252 ERASE NO FREEPAGE 0 PCTFREE 0 TRACKMOD YES COMPRESS YES , PART 2 USING STOGROUP STEVESG PRIQTY 252 SECQTY 252 ERASE NO FREEPAGE 0 PCTFREE 0 TRACKMOD YES COMPRESS YES , . ) BUFFERPOOL BP3 LOCKSIZE PAGE LOCKMAX 0 LOCKPART YES CLOSE YES CCSID EBCDIC; CREATE TABLESPACE ACTSACCG IN TAC4DB01 USING STOGROUP D3DPSMS PRIQTY 2880 SECQTY 7220 ERASE NO FREEPAGE 0 PCTFREE 5 TRACKMOD NO SEGSIZE 64 BUFFERPOOL BP3 LOCKSIZE PAGE LOCKMAX 0 LOCKPART NO CLOSE YES COMPRESS YES CCSID EBCDIC;

Copyright 2004, Cognizant Academy, All Rights Reserved

18

DB2 TABLES-Features
?? Table that is physically stored within a table space contains one or more stored

records. There will be one stored record per row in the base table (the table that is visible to the user).
?? Tables store the data in the form of c olumns of values attached to a specific data

type with allowable value constraints


?? The stored record is a byte string containing

o o o

A prefix denoting the internal system identifier For each field, a length prefix denoting the actual length, followed by the actual field value in an encoded form. RID Record identifier internally addresses the stored records. This consists of the page number within the table space and a byte offset from the foot of the page. This in turn contains the byte offset from the top of the page. This way when the records are rearranged within a page, the RID would not change. Only the local offset at the foot of the page will change.

Columns

Rows

EMPNO 10 20 30

FIRSTNME CHRISTINE MICHAEL SALLY

MIDINIT LASTNAME I HAAS L THOMPSON A KWAN

WORKDEPT A00 B01 C01

Special Registers:
They are Zero Argument built-in Scalar functions, which return a scalar value.
?? USER - Returns the primary Authorization ID. ?? CURRENT SQLID - Returns the Current Authorization ID - This could be primary Id

or secondary ID assigned to a specific functional area.


?? CURRENT SERVER - Returns the ID of the current server (useful in Distributed

Database mgmt)
?? CURRENT PACKAGESET - Returns ID of the collection that is currently in use. ?? CURRENT DATE/TIME/TIMESTAMP - Returns the Current Date/ Time /Timestamp. ?? CURRENT TIMEZONE - Returns a time duration representing the displacement of

the local time zone from Greenwich Mean Time.

Copyright 2004, Cognizant Academy, All Rights Reserved

19

DB2
DDL for Creating Table: CREATE TABLE DEPARTMENT (DEPTNO ,DEPTNAME ,MGRNO ,ADMRDEPT ,LOCATION ) -----IN <DATABASE>.<TABLESPACE> (The default is used if not specified) ; Note: Table can also be created as CREATE TABLE DUPDEPT1 LIKE DEPARTMENT; CREATE TABLE DUPDEPT2 LIKE DEPARTMENT (DEPT_PHONE CHAR (10)); CHAR(3) NOT NULL VARCHAR(29) NOT NULL CHAR(6) CHAR(3) NOT NULL WITH DEFAULT '200' CHAR(16) NOT NULL WITH DEFAULT

,PRIMARY KEY(DEPTNO)

CREATE TABLE EMPLOYEE (EMPNO ,FNAME ,LNAME CHAR(6) NOT NULL VARCHAR(12) NOT NULL VARCHAR(15) NOT NULL

,WORKDEPT CHAR(3) ,PHONENO CHAR(7) ,HIREDATE DATE ,JOB CHAR(8) ,SEX CHAR(1) ,DOB DATE ,SALARY DECIMAL(9,2) ,BONUS DECIMAL(9,2) ,COMM DECIMAL(9,2) ,PRIMARY KEY(EMPNO)) WITH RESTRICT ON DROP --> this will avoid table from getting dropped. ; DDL for Alter Table: E.g.: ALTER TABLE EMPLOYEE ADD TAX DECIMAL (9,2); And this command is also used to add or drop constraint - Primary/Foreign keys/check

Copyright 2004, Cognizant Academy, All Rights Reserved

20

DB2 Types of Constraints:


Check Constraint:
?? Used to enforce specific restriction on the values of a column.This will be checked for

every update/insert.
?? Can use Condition Operators, BETWEEN, IN, LIKE, NULL and can have multiple

conditions combined using 'AND' / 'OR' Example: CONSTRAINT PHONE_CHK CHECK (PHONENO >= '0000000' AND PHONENO <= '9999999') The 2nd operand can be another column. But they should be of same data type as first. Advantages:
?? The basic business rules that need to be applied can be done at the database level.

And this can save additional programming in applications that modify that data.
?? It ensures consistency and data integrity as

o o
??

It avoids bypassing of rules by ad-hoc data modification The rules are applied every time data is modified If the conditions coded contradict each other, like Check (Phone no > '1000000' and Phone no < '0999999') If the conditions coded contradict the defaults Redundant conditions are allowed - this could impact performance

Watch out the following- (these are not checked)

?? ??

Referential Integrity: Means of ensuring data integrity between related tables using a parent-child relationship. The one with Primary key is parent. The one with foreign key is child table. Example: Alter Table EMPLOYEE Foreign Key Fkey1 (workdept) References Department ON DELETE CASCADE Alter Table EMPLOYEE Foreign Key Fkey2 (workdept) References Department ON DELETE RESTRICT Alter Table DEPARTMENT Foreign Key Fkey3 (ADMRDEPT) References Department ON DELETE CASCADE Copyright 2004, Cognizant Academy, All Rights Reserved

21

DB2
(A self-referencing constraint should always use 'ON DELETE CASCADE)' Alter Table DEPARTMENT Foreign Key Fkey4 (MGRNO) References Employee ON DELETE SET NULL Note: - The same constraint when enforced through the application, consumes more resources. Primary Key It is a unique identifier for each row in a table. It can be made of one or more columns. These columns can never be NULL. Note: - A table can be defined without a primary key. But it is available for use only if the uniqueness is enforced by defining a UNIQUE INDEX on the same columns. Other Integrity Constraints:
?? Checking of Data types ?? Checking NOT NULL ?? Based on unique index on columns not defined as primary key/ alternate key.

INDEX
An index is an ordered set of pointers to rows of a base table. Or An Index is a balanced B-tree structure that orders the values of columns in a table

?? Index is a logical entity that defines the logical ordering imposed on the stored data. ?? Each index is based on the values of data in one or more columns. An index is an

object that is separate from the data in the table. When you define an Index using the CREATE INDEX statement, DB2 builds this structure and maintains this automatically.
?? They are used to access data directly and more efficiently. ?? In most cases access to data is faster with an index ?? Indexes are used to enhance performance and ensure uniqueness. ?? A table with Unique index cannot have rows with identical keys. ?? For each distinct value of the index, the pointers, i.e. the RIDs of all the stored

records that have that value are stored.


?? Index Scan is used when an exhaustive search is to be done based on the index

value. This is based on the sequence in which the indexed values are stored.
?? Tablespace scan is based on the physical sequence of the records.

Copyright 2004, Cognizant Academy, All Rights Reserved

22

DB2
?? Clustering Index is one for which the records are physically maintained in the

sequence defined by the index. The index controls the physical placement of the indexed records.

Syntax for creation of an Index:

CREATE INDEX <indexname> ON <tabname> (colname asc/desc) Index Parameters for Creation
?? CLUSTER ?? USING STOGROUP/VCAT (the corresponding name) ?? FREEPAGE ?? PCTFREE ?? PRIQTY / SECQTY ?? BUFFERPOOL ?? CLOSE - Yes/No ?? ERASE Yes/No

Example: CREATE UNIQUE INDEX SACM2.ACICACCT ON SACM2.ACTBACCT (ACCT_ID CLUSTER (PART 1 VALUE ('4384340002425997') USING STOGROUP DUDTSMS PRIQTY 25200 SECQTY 7200 ERASE NO FREEPAGE 31 PCTFREE 15 ,PART 2 VALUES('4851270009632812') USING STOGROUP DUDTSMS PRIQTY 25200 SECQTY 7200 ERASE NO FREEPAGE 31 PCTFREE 15 ) Copyright 2004, Cognizant Academy, All Rights Reserved ASC)

23

DB2
BUFERPOOL BP4 CLOSE YES; CREATE UNIQUE INDEX RACA.ACI1SPAA ON RACA.ACTBSPAA (ACCT_ID PRIQTY 360000 SECQTY 131068 ERASE NO FREEPAGE 0 PCTFREE 10 BUFFERPOOL BP4 CLOSE YES PIECESIZE 2097152 K; ASC) USING STOGROUP D2DPSMS

Index Guidelines - What to do?


?? Consider indexing on columns used in UNION, DISTINCT, GROUP BY, ORDER BY

& WHERE clauses.


?? Limit the indexing of frequently updated columns ?? Create explicitly, a clustering index ?? Create a Unique index on the primary key and indexes on foreign keys ?? Overloading of index when row length of a table to be accessed is short. ?? At least one index must be defined for a table with more than 100 pages ?? Use Multicolumn index rather than a multi-index (application dependent); however

the latter requires more DASD.


?? Create indexes before loading the table. ?? Clustering reduces I/O; DB2 optimizer usually tries to use an index on clustered

column before using the other indexes.


?? Specify Indexspace Freespace the same as Tablespace Freespace ?? Use the DEFER option while creating the index. RECOVER INDEX utility can then be

used to populate the index. Recover utility populates index entries faster.
?? Use different STOGROUPs for Tablespaces & Indexspaces ?? Create Critical indexes in a different Bufferpool than the Tablespaces.

Index Guidelines - What NOT to do?


?? Avoid indexing on Variable columns ?? Limit the number of indexes on partitioned TS ?? Avoid indexes if

The table is very small (< 10 pages)

Copyright 2004, Cognizant Academy, All Rights Reserved

24

DB2
o o It has heavy inserts and deletes and is relatively small (< 20 pages) It is accessed with a scan.

?? Avoid defining redundant indexes

INDEXSPACE
?? There is always a one-to-one correspondence between index and index space. Index

space is automatically created when we create an index.


?? They can be partitioned if the index it contains is a clustering index for a partitioned

table space. Others are simple.


?? It is the unit of recovery and reorganization. For partitioned Index space, individual

partitions can be reorganized or recovered.

VIEWS
Views are a logical derivation of a table from other table/tables. Or Views are virtual tables based on one or more base tables. Features of Views:
?? A View does not exist in its own right. ?? They provide a certain amount if logical independence ?? They allow the same data to be seen by different users in different ways ?? When data in the base table changes, these changes are also reflected in the view. ?? The view is executed only when it is accessed ?? In DB2, a view that has to accept an Update must be derived from a single base

table. We cannot perform Insert/ Update /Delete in a View with


?? Joins ?? Functions ?? Distinct ?? Group By and Having

We cannot perform Insert in a View with


?? Derived Data ?? Constants ?? Without columns that dont have default value

They must be defined for a specific use and for one of the following advantages they provide
?? To provide row and column level security

Copyright 2004, Cognizant Academy, All Rights Reserved

25

DB2
o By limiting the select items to the columns to which the user should have access and/or by limiting the rows by using proper conditions in WHERE clause. By using join criteria and by using indexed columns in predicates By using data derivation formulas in the select list

?? To ensure optimal access

o o

?? To ensure same calculation

?? To Mask complexity of a query from DB2 beginners ?? To rename the columns so that the user can understand them better. ?? To Support Domains

Note: - Domain refers to a valid range of values that a column can contain. The Table CHECK Constraint is used to create the domains.

The WITH CHECK OPTION is used to ensure that the data modification using U pdate/Insert conforms to the WHERE conditions specified in the view definition. This option is of 2 types: WITH CASCADED CHECK OPTION The check option is applied to the current view and all the views it accesses regardless of whether it is specified or not. WITH LOCAL CHECK OPTION The check option is applied to the views where it is specified.

Syntax CREATE VIEW <View name> (<columns>) AS Subquery (Subquery - SELECT FROM other Table(s)) E.g.: CREATE VIEW HIGH_PAID_EMP (EMP_NO, EMP_FIRST_NAME, EMP_LAST_NAME, DEPT, JOB, SALARY) AS SELECT EMPNO,FNAME,LNAME,WORKDEPT,JOB, SALARY FROM EMP WHERE SALARY > 75000 WITH CHECK OPTION

SYNONYMS-What is it?
?? An alternative private name for a table or a view ?? It can be used only by its Creator. ?? It cannot refer to a remote table. ?? When a table/view is dropped, all synonyms defined on it are also dropped

Copyright 2004, Cognizant Academy, All Rights Reserved

26

DB2
Syntax CREATE SYNONYM <Synonym name> FOR <Tablename> Example: CREATE SYNONYM TESTSYS FOR <CREATOR>.<TABLENAME>

ALIASES
?? An alternative private name for a table or a view ?? It can be used by users other than its creator. ?? It can refer to a remote table. ?? When a table/view is dropped, all aliases defined on it are NOT dropped ?? Alias is created for a remote table, thereby giving it a shorter, local name because it

no longer requires the location prefix. Syntax CREATE ALIAS <Aliasname> FOR <Tablename>

Example: CREATE ALIAS TESTALS FOR <CREATOR>.<TABLENAME> Use Synonyms for Program Development, use Aliases for Distributed Applications and use Views for security and joining.

DB2 Data types


Equivalent COBOL Declaration PIC X (n) PIC COMP PIC X(n) Numeric SMALLINT INTEGER DECIMAL (p,s) FLOAT (n) 2 4 INTEGER (p/2) +1 8 (Single precision if n>21) PIC COMP PIC S9 COMP S9(4) (9) S9(4)

Data Type CHAR (n) String VARCHAR (n)

Internal Length N Max=n+2

Default Value Blanks String Zero Zero of length

PIC S9(p)V9(s) COMP-3 COMP-2

Copyright 2004, Cognizant Academy, All Rights Reserved

27

DB2
4 (Double precision if n<21) DATE Date/Time TIME TIMESTAMP 4 3 10 COMP-1 PIC X (10) PIC X (8) PIC X (26) Current Date Current Time Current Timestamp

Null Null represents the state where a field does NOT have any value. (It is not SPACES or LOW-VALUES).
?? Null - records missing or unknown information. ?? Either the Column does not a pply for the row (inapplicable data) or the value does

not exist currently (unknown data).


?? Represented by special Indicator Variables. ?? An Indicator variable is provided for each column that allows nulls. This is transparent

to the user but must be provided during programming.


?? By Default a field is allowed to be NULL. Nulls can be prohibited by specifying NOT

NULL or NOT NULL WITH DEFAULT during column definition.

Test your Understanding


1). Which one of the following is the Index parameters? A. CLUSTER B. ERASE C. FREEPAGE D. All of the above

Copyright 2004, Cognizant Academy, All Rights Reserved

28

DB2

Chapter 3: SQL
Learning Objectives
The chapter shall achieve the following objectives:
?? Knowing what is SQL ?? Knowing the advantages of SQL

Introduction to SQL SQL or Structured Query Language is


?? A Powerful language that performs the functions of data manipulation (DML), data

definition (DDL) and data control or data authorization (DAL/DCL).


?? A Non procedural language - the capability to act on a set of data and the lack of

need to know how to retrieve it. An SQL can perform the functions of more than a procedure.
?? The De Facto Standard query language for RDBMS. It is used by many Relational

database products like DB2, Oracle, and Sybase etc.


?? Very flexible

SQL Features:
?? It is a high level language as compared to procedural languages like COBOL -

because it provides a greater degree of abstraction. In procedural languages, we process record by record we specify what data is to be accessed and how to access them.
?? SQL on the other hand requires that that programmer specify only what is needed,

but cannot specify how to retrieve them. The optimal instructions for data navigation (called the access path) are determined by the database itself. This is advantageous because the database knows better how it has stored data than the user.
?? SQL is not only a query language but it is also used to define data structures,

insert, modify, delete data and control access to the data. The language is common to different users like DBAs, application programmers, etc.
?? All database operations using SQL are at Set-Level unlike record level processing

using flat files. This includes querying a table and the result is in the form of a subset of the original table. Similarly, updates and deletes also can be done at set level. SQL Selection and Projection:
?? Select retrieves a specific number of rows from a table ?? Projection operation retrieves a specified subset of columns (but all rows) from the

table Projection E.g.. : SELECT CUST_NO, CUST_NAME FROM CUSTOMER Selection

Copyright 2004, Cognizant Academy, All Rights Reserved

29

DB2

WHERE OFFICE_CD IN (02, 04)

?? The WHERE

clause defines the Predicates for the SQL operation. clause can have multiple conditions using AND & OR.

?? The above WHERE

Other Clauses: Many other clauses can be used in conjunction with the WHERE clause to code the required predicate, some are: ?? Between / Not Between ?? In / Not In ?? Like / Not Like ?? IS NULL / IS NOT NULL

QMF (Query Management Facility)


?? It is an MVS- and VM- based query tool ?? It allows end users to enter SQL queries to produce a variety of reports and graphs

as a result of this query


?? QMF queries can be formulated in several ways: - By direct SQL statements, by

means of relational prompted query interface or by query-by-example (QBE). QBE is similar to SQL in some ways but more user-friendly

SPUFI
?? It supports the online execution of SQL statements from a TSO terminal ?? Used for developers to check SQL statements or view table details ?? SPUFI menu contains the input file in which the SQL statements are coded, option

for default settings and editing and the output file.


?? Enter option 8.1 on the Cognizant M/F main menu. Provide the input/output datasets.

Types of SQL
Based on the type of usage, SQL can be classified into 2 Categories ?? Static SQL It is embedded in an application program written in a high-level

language like Cobol.


?? Dynamic SQL It could be embedded in an application program where it will be

constructed at run-time. Or it could be executed online at a terminal. Based on Functionality, SQL can be classified into 3 Categories
?? DDL ?? DML

Copyright 2004, Cognizant Academy, All Rights Reserved

30

DB2
?? DCL

Definition Language (DDL)


Creates and maintains physical data structures using CREATE, ALTER and DROP verbs.

Create Table

Format: CREATE TABLE <Table_name > ( Col Name Datatype,) PRIMARY KEY (Columns) FOREIGN KEY <Name> (Column) REFERENCES dbname.tablename ON DELETE (SET NULL/CASCADE) UNIQUE (Col name) (referential constraint) 1. LIKE Table name / View name 2. IN Database Tablespace Name
?? Foreign Key references dbname.tablename on relation condition for delete. ?? If Table1 references Table2 (target) - Table2s Primary key is the

foreign key

defined in Table1
?? The Conditions are CASCADE, RESTRICT & SET NULL (referential constraint for

the foreign key definition)


?? Inserting (or updating) rows in the target is allowed only if there are no rows in the

referencing table

General Rules for Referential Integrity and Table Parameters


?? Avoid nulls in columns participating in Arithmetic logic or comparisons ?? Primary key columns cannot be nulls ?? Limit referential structures to no more than three levels in a direction ?? Use DB2s inherent features rather than program coded RIs. ?? Do not use RIs on tables built from another RI system ?? Consider using Fieldprocs or Editprocs or Validprocs

Alter Table

Format:
ALTER: ALTER TABLE <Tablename> ADD Column Data-type [ not null with default]

Copyright 2004, Cognizant Academy, All Rights Reserved

31

DB2
Alter allows Primary & Foreign key specifications to be changed It does not support changes to width or data type of a column or dropping a column Drop Table Format: DROP: DROP TABLE <Tablename> Similar statements are there for other database objects

Data Manipulation Language


Accesses and Modifies Data using INSERT, SELECT, UPDATE and DELETE Insert Syntax

INSERT INTO Tablename(column1,

column2, column3 ,......)

VALUES(value1, value2, value3 ,........) If any column is omitted in an INSERT statement and
?? If that column is NOT NULL, then INSERT fails ?? If nullable it is set to NULL. ?? If the column is defined as NOT NULL BY DEFAULT, it is set to that default value

Omitting the list of columns is equivalent to specifying all values

Syntax for INSERT using SELECT INSERT INTO TEMP (A#, B) SELECT A#, SUM (B) FROM TEMP1 GROUP BY A# ; Select Syntax SELECT <column list> FROM <table_name> {WHERE <search_condition> } - optional {GROUP BY <grouping cols> } - optional {HAVING <group search> } {ORDER BY <sort_order> } The search can use the following
?? Comparison Operators

- optional - optional

Copyright 2004, Cognizant Academy, All Rights Reserved

32

DB2
?? Logical Connectors

Comparison Operators
The following operators are used for comparisons. The comparisons that can take place are
?? Numeric data can only be compared with numeric data; data conversion from one

form to another might be done to facilitate the operation.


?? Character data is compared character by character from left to right. The Collating

sequence used for comparison is EBCDIC. o o o o o o = EQUAL TO ~= (Or <>) NOT EQUAL TO < LESS THAN > GREATER THAN <= LESS THAN OR EQUAL TO >= GREATER THAN OR EQUAL TO

Logical Connectors These are used to obtain logical TRUE values. These must not be used with logical operators. These are used to specify more than one criterion in the search clause.
?? AND, OR, NOT

E.g. for Simple Select: Single Row Select SELECT EMPNO, FIRSTNME, MIDINIT, LASTNAME, WORKDEPT FROM DSN8710.EMP WHERE EMPNO = '000010' EMPNO FIRSTNME 000010 CHRISTINE MIDINIT LASTNAME WORKDEPT I HAAS A00

E.g. for Multi Row select SELECT EMPNO, FIRSTNME, MIDINIT,LASTNAME,WORKDEPT FROM DSN8710.EMP WHERE MIDINIT = 'R'

EMPNO 160 280 290 340 200280 200340

FIRSTNME ELIZABETH ETHEL JOHN JASON EILEEN ROY

MIDINIT LASTNAME WORKDEPT R PIANKA D11 R SCHNEIDERE11 R PARKER E11 R GOUNOT E21 R SCHWARTZ E11 R ALONZO E21

Many other clauses can be used in conjunction with the WHERE clause to code the required predicate, some are: Copyright 2004, Cognizant Academy, All Rights Reserved

33

DB2

Between/Not Between E.g.: SELECT EMPNO,FIRSTNME,MIDINIT,LASTNAME,WORKDEPT FROM DSN8710.EMP WHERE EMPNO BETWEEN '000150' AND '000200' IN/Not IN E.g.: SELECT EMPNO,FIRSTNME,MIDINIT,LASTNAME,WORKDEPT FROM DSN8710.EMP WHERE EMPNO IN ('000150' ,'000200') LIKE/Not LIKE E.g.: SELECT EMPNO,FIRSTNME,MIDINIT,LASTNAME,WORKDEPT FROM DSN8710.EMP WHERE FIRSTNME LIKE 'J%' WITH UR; Note: - _ for a single char ; % for a string of chars Escape \ - escape char; if precedes _ or % overrides their meaning

EMPNO 50 190 220 230 290 340

FIRSTNME JOHN JAMES JENNIFER JAMES JOHN JASON

MIDINIT B H K J R R

LASTNAME WORKDEPT GEYER E01 WALKER D11 LUTZ D11 JEFFERSOND21 PARKER E11 GOUNOT E21

NULL/NOT NULL:

To check for null the syntax is IS NULL or IS NOT NULL.

E.g.:
SELECT * FROM DSN8710.DEPT WHERE MGRNO IS NULL; Remember NULL is NOT spaces

Copyright 2004, Cognizant Academy, All Rights Reserved

34

DB2

DEPTNO D01 F22 G22 H22 I22 J22


Functions

DEPTNAME DEVELOPMENT CENTER BRANCH OFFICE F2 BRANCH OFFICE G2 BRANCH OFFICE H2 BRANCH OFFICE I2 BRANCH OFFICE J2

MGRNO -------------------------------

ADMRDEPT A00 E01 E01 E01 E01 E01

There are two types of Functions:


?? One that acts on a particular column in all rows that got selected: -Aggregate

(Column) Function.
?? One that acts on one row at a time: - Scalar Functions

Aggregate Functions Compute from a group of rows aggregate value for a specified column(s) AVG, COUNT, MAX, MIN, SUM
?? AVG gets the average value of a set of numeric values, which are not Null. ?? MAX gets the maximum value of a set of values. ?? MIN gets the minimum value of a set of values. ?? SUM gets the sum of numeric values, which are not null.

Note: All the 4 return Null when no matching rows are found.
?? COUNT

o o o o

Count (*) -Gets a count of matching rows Count (All/Distinct expression) gets a count of rows with non-null value for the expression. It returns 0 when no rows satisfy a Where clause It returns 0 rows when used with a Group By

?? COUNT_BIG Similar to count used when the count is too large

E.g.: SELECT AVG(SALARY) A00_AVGSAL FROM DSN8710.EMP WHERE WORKDEPT = 'A00'

Some Rules for Column Functions:


?? Column functions can be executed only in SELECT Statements ?? A column function must be specified for an explicitly named column or expression

Copyright 2004, Cognizant Academy, All Rights Reserved

35

DB2
?? Each column function returns only one value for the set of selected rows. ?? If you apply a column function to one column in a SELECT statement, you must apply

column functions to any other columns specified in the same SELECT statement, unless you also use the GROUP BY clause.
?? The result of a column function (except the COUNT function) will have the same data

type as the column to which it was applied. The COUNT function returns an integer number.
?? The result of any column function (except the COUNT function) can be null. COUNT

always returns a numeric result.


?? Column functions will not return a SQLCODE of +100 if the predicate specified in the

WHERE clause finds no data. Instead, a null is returned.


?? When using the AVG, MAX, MIN and SUM functions on nullable columns, all

occurrences of null are eliminated before applying the function.


?? You can use the DISTINCT keyword with all column functions to eliminate duplicates

before applying the given function. DISTINCT has no effect, however, on the MAX and MIN functions. Scalar Functions Are applied to a column or expression and operate on a single value. CHAR, DATE, DAY (S), DECIMAL, DIGITS, FLOAT, HEX, HOUR, INTEGER, LENGTH, MICROSECOND, MINUTE, MONTH, SECOND, SUBSTR, TIME, TIMESTAMP, VALUE, VARGRAPHIC, YEAR CHAR: Converts DB2 date, time, timestamp, or decimal value to a character value. DATE: Converts a value representing a date to a DB2 date. The value to be converted can be a DB2 timestamp, a DB2 date, a positive integer, or a character string. DAY: Returns the day portion of a DB2 date or timestamp.

DAYS: Converts a DB2 date or timestamp into an integer value representing one more than the number of days since January 1, 0001. DECIMAL: Converts any numeric value to a decimal value INTEGER: Converts any number to an integer by truncating the portion of the number to the right of the decimal point. LENGTH: Returns the length of any column, which may be a null STRIP: Removes leading, trailing or both leading and trailing blanks (or any specific character) from a string expression SUBSTR: Returns specified portion of a character column from any starting point to any ending point. TIMESTAMP: Obtains a timestamp from another timestamp, a valid character-string Copyright 2004, Cognizant Academy, All Rights Reserved

36

DB2
representation of a timestamp, or a combination of date and time values. E.g.: SELECT SUBSTR(DEPTNAME,1,7) FROM DSN8710.DEPT

Some Rules for Scalar Functions:


?? Scalar functions can be executed in the select list of the SQL SELECT statement or

as part of a WHERE or HAVING clause.


?? A scalar function can be used wherever an expression can be used. ?? The argument for a scalar function can be a column function.

Arithmetic Functions
The Valid symbols are + - * / ( ) SELECT BONUS+COMM VARIABLE_COMP FROM DSN8710.EMP WHERE WORKDEPT = 'A00' SELECT EMPNO, (SALARY/12) MONTHLY_GROSS FROM DSN8710.EMP WHERE WORKDEPT = 'A00'
VARIABLE_COMP 5220.00 4620.00 2940.00 5220.00 2940.00

EMPNO 000010 000110 000120 200010 200120

MONTHLY_GROSS 4395.83333333 3875.00000000 2437.50000000 3875.00000000 2437.50000000

Duplicates
Duplicates are eliminated using DISTINCT SELECT DISTINCT WORKDEPT FROM DSN8710.EMP

Sorting Records
The result-set from the query (with a where clause) is sorted based column(s) in a specific order using the ORDER BY clause ORDER BY <column_name or position> ASC or DESC (Default is ASC)

SELECT EMPNO,FIRSTNME,MIDINIT,LASTNAME,WORKDEPT
FROM DSN8710.EMP Copyright 2004, Cognizant Academy, All Rights Reserved

37

DB2
ORDER BY WORKDEPT( or 5) ASC

Rules for Order By:


?? Order by cannot be used on intermediate results (sub-query) ?? We can order by a column that is not in the SELECT list ?? We can order by an expression. E.g.: - ORDER BY SUBSTR(EMPNO,2)

Grouping Records
Used to combine multiple rows into 1. HAVING clause is used to select which of the groups are to be retrieved.
?? Used when aggregate functions are used along with regular columns. ?? Group by operator causes the table represented by the FROM clause to be

rearranged into groups, such that within one group all rows have the same value for the Group by column (not physically in the database).
?? The Select

clause is applied to the grouped data and not to the original table.

Here HAVING is used to eliminate groups, just like WHERE is used for rows. Example: 1) Find the Max salary in each department among employees hired after 1965-01-01 SELECT WORKDEPT DEPARTMENT, MAX(SALARY) MAX_SALARY FROM DSN8710.EMP WHERE HIREDATE > '1965-01-01' GROUP BY WORKDEPT
?? WHERE is used on a column ?? HAVING is used on aggregate data

2) Find the Max salary among employees hired after 1965-01-01 in each department that has Max Salary more than 30,000. SELECT WORKDEPT DEPARTMENT,MAX(SALARY) MAX_SALARY FROM DSN8710.EMP WHERE HIREDATE > '1965-01-01' GROUP BY WORKDEPT HAVING MAX(SALARY) > 30000

Rules for Group By:


?? There can be only one Group By per Select. ?? The SELECT items must either be on the Group By or they must be Column

Functions.
?? The result of the query should have a distinct set or rows where the unique identifier

is the field(s) grouped on.


?? All Null values in the Group By fields are considered equal.

Copyright 2004, Cognizant Academy, All Rights Reserved

38

DB2
?? We

can group by fields as well as expressions. E.g.: GROUP BY SUM (Salary+Comm)

Complex SQLs
An SQL is said to be complex when data that is to be retrieved comes from more than one table A Complex SQL contains one or both of
?? Joins ?? Subqueries

Joins
?? Data can be selected from multiple tables by joining the tables on common columns ?? Data is retrieved based on matching key values (Join Criteria) ?? Joins can be done using any of the Comparison operators

SELECT

tableA.column3, tableA.column4, tableB.column1, tableB.column3

FROM WHERE AND

tableA, tableB tableA.primary = tableB.foreign optional search criteria

Join Example

Find the Department details of the Employee 000060. SELECT A.EMPNO, A.FIRSTNME, A.LASTNAME, A.WORKDEPT, B.DEPTNAME, B.MGRNO FROM DSN8710.EMP A, DSN8710.DEPT B WHERE A.WORKDEPT=B.DEPTNO AND A.EMPNO = '000060'

EMPNO FIRSTNME LASTNAME WORKDEPT DEPTNAME MGRNO 000060 IRVING STERN D11 MANUFACTURING 000060

Copyright 2004, Cognizant Academy, All Rights Reserved

39

DB2 Types of Joins


OUTER JOIN: For one or more tables being joined, both matching and non-matching rows are returned. Duplicate columns may be eliminated The non-matching columns will have nulls in them. SELECT A.EMPNO, A.FIRSTNME, A.LASTNAME, A.WORKDEPT, B.DEPTNAME, B.MGRNO FROM DSN8710.EMP A FULL OUTER JOIN DSN8710.DEPT B ON A.WORKDEPT=B.DEPTNO ORDER BY 1
?? Useful when we want rows that have the matching values and also the ones that

dont have matching rows in the other table.


?? LEFT - All rows in first table plus matching rows in 2nd table. ?? RIGHT - All rows in 2nd table plus matching rows in 1st ?? FULL - All rows in 1st and 2nd table plus matching rows.

INNER JOIN (Default):


In Inner join, only the matching rows are displayed. Hence there is a possibility that one or more of the rows from either or both tables being joined will not be included in the table that results from the join operation. Subqueries Subqueries are nested SELECT statements.
?? They are specified using the IN(or NOT IN) predicate, equality or non-equality

predicate(= or <>) and comparative operator(<, <=, >, >=).


?? They are used to relate one table to another or multiple others without doing a Join. ?? When using the equality, non-equality or comparative operators, the inner query

should return only a single value


?? The nested loop statements gives the user the flexibility for querying multiple tables.

Syntax: Expression OP SOME/ANY/ALL (SUBQUERY) OR Expression (NOT) EXISTS/IN (SUBQUERY) SOME: The subquery is true if any row matches (same for ANY) ALL: The subquery is true ONLY if ALL rows match IN: matches one of the values listed by the subquery EXISTS: there exists at least one matching row in the subquery. There are 2 types of Subquery: Uncorrelated Subquery (Non correlated subquery) In this type, the result of the Subquery has no direct relationship with the current row from the Main Query. This works in a Bottom-to-Top fashion. Copyright 2004, Cognizant Academy, All Rights Reserved

40

DB2
Examples: i) Locate the Project information of Employee whose first name is Christine SELECT PROJNO , PROJNAME FROM DSN8710.PROJ WHERE RESPEMP =( SELECT EMPNO FROM DSN8710.EMP WHERE FIRSTNME = 'CHRISTINE')

ii) Locate the dept information of all employees with a specific Hire Date. SELECT DEPTNO , DEPTNAME FROM DSN8710.DEPT WHERE DEPTNO IN ( SELECT WORKDEPT FROM DSN8710.EMP WHERE HIREDATE IN ('1947-05-05', '1963-12-05')); Note: A join is always preferred over a Subquery. E.g. Query (i) of above can be re written as: Locate the Project information of Employee whose first name is Christine SELECT PROJNO, PROJNAME FROM DSN8710.PROJ A, DSN8710.EMP B WHERE B.EMPNO= A.RESPEMP AND B.FIRSTNME = 'CHRISTINE'

Copyright 2004, Cognizant Academy, All Rights Reserved

41

DB2
Correlated Subquery In this kind of subquery, the result of the subquery can be evaluated only based on the value in the current row. It works on Top-to-Bottom-to-Top fashion.

E.g.: Get the Employee details of all Managers SELECT FIRSTNME, SALARY, WORKDEPT FROM DSN8710.EMP A WHERE WORKDEPT IN (SELECT DEPTNO FROM DSN8710.DEPT B WHERE B.MGRNO = A.EMPNO) SELECT EMPNO, WORKDEPT, DEPTNAME FROM EMPLOYEE A WHERE WORKDEPT = ANY(SELECT DEPTNO FROM DEPARTMENT); SELECT EMPNO, WORKDEPT, DEPTNAME FROM EMPLOYEE A WHERE WORKDEPT = SOME(SELECT DEPTNO FROM DEPARTMENT); SELECT EMPNO, WORKDEPT, DEPTNAME FROM EMPLOYEE A WHERE WORKDEPT IN (SELECT DEPTNO FROM DEPARTMENT); SELECT * FROM EMPLOYEE A WHERE A.SALARY >= ALL (SELECT SALARY FROM EMPLOYEE B)

Correlated Subquery using EXISTS clause:


?? Checks for the existence of a row matching the criteria. ?? The columns values do not matter

E.g.: - List all employees who are responsible for at least one project. SELECT EMPNO FROM DSN8710.EMP A WHERE EXISTS (SELECT 1 FROM DSN8710.PROJ P WHERE P.RESPEMP = A.EMPNO)

Copyright 2004, Cognizant Academy, All Rights Reserved

42

DB2
Similarly a NOT EXISTS is used for checking the negative value and is preferred over a NOT IN when column values dont matter. E.g.: - Select those Departments that have no employees

SELECT A.DEPTNO, A.DEPTNAME FROM DEPARTMENT A WHERE NOT EXISTS (SELECT DISTINCT(B.WORKDEPT) FROM EMPLOYEE B WHERE B.WORKDEPT = A.DEPTNO) OR SELECT A.DEPTNO, A.DEPTNAME FROM DEPARTMENT A WHERE NOT IN (SELECT DISTINCT(B.WORKDEPT) FROM EMPLOYEE B)

Multiple levels of Subquery: SELECT Cust-no, Cust-name, Cust-addr FROM CUSTOMER A WHERE Order-no IN (SELECT order-no FROM ORDER B WHERE Prod-id IN (SELECT Prod-id FROM PRODUCTS WHERE Prod-name = NUTS));

Copyright 2004, Cognizant Academy, All Rights Reserved

43

DB2 Union

UNION combines 2 sets of rows into a single set composed of all the rows in either or both of the original union sets. For two sets/queries to be compatible for Union,
?? The two sets must contain the same no of columns ?? Each column of the first set must be either the same data type as the corresponding

column of the second or must be convertible.

Union verb eliminates duplicates and retrieves distinct records. UNION ALL retains the duplicates. E.g.: SELECT EMPNO FROM DNS8710.EMP WHERE LASTNME = HAAS UNION SELECT EMPNO FROM DSN8710.EMP WHERE JOB= PRES; The UNION verb can be replaced by an OR: SELECT EMPNO FROM DSN8710.EMP WHERE LASTNME = HAAS OR JOB = PRES
?? Union would suppress any duplicates ?? If the two selects are from different tables, UNION cannot be replaced by OR.

Copyright 2004, Cognizant Academy, All Rights Reserved

44

DB2
Update UPDATE tablename SET Columnname(s) = scalar expression (,) WHERE [ condition ]
?? Single or Multiple row updates can be performed. ?? Update can also be done with a Subquery

Delete DELETE FROM Tablename WHERE [condition];


?? Single or multiple row delete ?? Deletion of all rows

Data Control Language


Control Data Security using GRANT and REVOKE

Grant
?? GRANT: grants the table privileges, plan & package privileges, collection privileges,

database privileges, use privileges and system privileges


?? User with a SYSADM privilege will be responsible for overall control of the system. ?? The table privileges allowed are SELECT, UPDATE, DELETE, INSERT, (both base

tables & views), ALTER (Table) & (Create) INDEX (only to base tables)
?? There are no specific DROP privileges; the table can be dropped by its owner or a

SYSADM

Format of GRANT:
GRANT SELECT, UPDATE (NAME, NO) ON TABLE EMPL TO A, B, C (or PUBLIC); GRANT ALL ON EMPL TO PUBLIC; GRANT EXECUTE ON PLAN PLANA TO USER; A user having authority to grant privilege to another, also has the authority to grant the privilege with with the GRANT Option

Revoke
?? This statement revokes the privileges given to a user. The user granting the

privileges has the authority to REVOKE also.


?? It is not possible to be column specific when revoking an UPDATE privilege ?? REVOKE SELECT ON TABLE EMPL FROM USERA;

Copyright 2004, Cognizant Academy, All Rights Reserved

45

DB2 Test your Understanding


1). In Dynamic SQL A. Access Path is not determined before execution B. Hard coded in the application program C. Statements can change throughout the program execution D. Option 1 & 3 2). Host variables is a A. Columns in Table B. Defined in SQL statements C. Working Storage variable D. None of the above

Answer: 1). D 2). C

Copyright 2004, Cognizant Academy, All Rights Reserved

46

DB2

Chapter 4: DB2 Application Programming


Learning Objectives
The chapter shall achieve the following objectives:
?? Knowing the steps involved in application programming ?? Knowing about Embedded SQL and Dynamic SQL

About Static SQL


?? These are hard-coded in the application program ?? They cannot be modified during the programs execution except for changes to the

values assigned to the host variables


?? Cursors are used to access set-level data ?? The general form is

EXEC SQL [SQL statements] END_EXEC

About Dynamic SQL


?? Statements can change throughout the programs execution ?? When the SQL is bound, the application plan or package that is created does not

contain the same information as that for a static SQL program


?? The access paths cannot be determined before execution.

Embedded SQL
For an application program to access DB2 data, the SQL statements have to be embedded in the program statements of the high level language like COBOL, PL1 etc. Embedded SQL can be executed in:
?? MVS Batch using CAF ?? TSO Batch ?? DL/I Batch ?? TSO (Interactive)

Copyright 2004, Cognizant Academy, All Rights Reserved

47

DB2

SQL statements that can be embedded are:

SQL DCL DDL DML Dynamic SQL Stored Procedures Embedding Control Transaction Control Package Control General Error Handling

SQL Types Grant, Revoke Create, Alter, Drop Insert, Select, Update, Delete Describe, Execute, Execute Immediate, Prepare Call, Allocate Cursor. Associate Locators Declare, Open, Fetch, Close Commit, Rollback Set Current Packageset Explain, Lock Table, Set Whenever

Comparison of Application that accesses data from Flat files Vs Application accessing DB2 data:

DB2 Access All the accessed tables are declared. Cursors are declared No DD card in JCL Cursors are opened Cursors are closed Set level processing Access to table can be at Column level Status of SQL returned by SQLCODE Cursors are used to simulate record level processing

File Access Files are defined in the FD section

DD card required except for files allocated dynamically Files are opened Files are closed Record level processing Always a full record is read or written Status indicated by file-status READ/WRITE used for record-level processing

Copyright 2004, Cognizant Academy, All Rights Reserved

48

DB2 Steps Involved in Application Programming A DB2 application program must go through a process known as Program Preparation before it can run successfully. The steps involved are depicted below:

Source Program Pre Compiler DCLGEN

Modified Source

DBRM

Compiler

Bind

Compiled Source (Object Module)

Application Plan

Link DB2 Directory DB2 Catalog

Load Module

Execute

Copyright 2004, Cognizant Academy, All Rights Reserved

49

DB2 Coding the application


Host Variables
?? These are variables (rather area of storage) defined in the host language to use the

predicates of a DB2 table. These are referenced in the SQL stmt.


?? A means of moving data from and to DB2 tables ?? DCLGEN produces host variables, the same as the columns of the table. This is

included in the source program. SELECT Cust_No, Cust_name, Cust_addr FROM CUSTOMER INTO :H-Cust-No, :H-Cust-name, :H-Cust-addr WHERE Cust_No = :H_Cust_No; Host variables can be used in
?? INTO Clause of SELECT & FETCH statements ?? As input of SET clause of UPDATE statements ?? As input for the VALUES clause of INSERT statement ?? In WHERE clause of SELECT, INSERT, UPDATE & DELETE ?? As literals in SELECT list of a SELECT statement

Host Structures
They are group level data containing a set of host variables and if all of them have to be used as the target of retrieval, the INTO will refer only to: Group data.

Embedded SQL
The SQL statements required in a program are embedded within EXEC SQL...END-EXEC statements (coded in column 12 or after).

EXEC SQL SQL Statements here . . END-EXEC.

?? It is similar to File I/O ?? Normally the embedded SQL statements contain the host variables coded in the

INTO or SELECT.... as shown above

Copyright 2004, Cognizant Academy, All Rights Reserved

50

DB2
SELECT, INSERT, UPDATE & DELETE statements can be coded inline

E.g.: EXEC SQL INSERT INTO EMP ( EMPNO, FIRSTNME, LASTNME, WORKDEPT) VALUES (:EMPNO, :FIRSTNME, :LASTNME, :WORKDEPT) END-EXEC

DCLGEN
DCLGEN command is issued on a table-by-table basis to produce a module that can be included in the DB2 application program. It reads the DB2 Catalog to determine the structure of the table and issues a COBOL Copybook. The Copybook contains a SQL DECLARE statement along with WORKING-STORAGE host variable definitions for each column in the table. The program will include the Copybook using the INCLUDE statement. A sample DCLGEN for an Employee table is :

************************************************************************* * DCLGEN TABLE(DSN8710.EMP) * * * * LIBRARY(U101823.DCLGEN.EMP) LANGUAGE(COBOL) QUOTE INDVAR(YES) * * * * *

* . IS THE DCLGEN COMMAND THAT MADE THE FOLLOWING STATEMENTS *

*************************************************************************
EXEC SQL DECLARE DSN8710.EMP TABLE ( EMPNO FIRSTNME MIDINIT LASTNAME CHAR(6) NOT NULL, VARCHAR(12) NOT NULL, CHAR(1) NOT NULL, VARCHAR(15) NOT NULL,

.
Copyright 2004, Cognizant Academy, All Rights Reserved

51

DB2 .
SALARY BONUS COMM ) END-EXEC. ****************************************************************** * COBOL DECLARATION FOR TABLE DSN8710.EMP ****************************************************************** 01 DCLEMP. 10 EMPNO 10 FIRSTNME. 49 FIRSTNME-LEN 49 FIRSTNME-TEXT 10 MIDINIT . . 10 SALARY 10 BONUS 10 COMM PIC S9(7)V9(2) USAGE COMP-3. PIC S9(7)V9(2) USAGE COMP-3. PIC S9(7)V9(2) USAGE COMP-3. PIC S9(4) USAGE COMP. PIC X(12). PIC X(6). * DECIMAL(9, 2), DECIMAL(9, 2), DECIMAL(9, 2)

PIC X(1).

The above DCLGEN is included in the program as follows:

EXEC SQL INCLUDE DCLEMP END-EXEC.

However, it is not mandatory that only this copybook should be used in the program. We can also hardcode the same information in the program, but that is not a good practice.

SQLCA (SQL Communication Area)


SQLCA is a DB2 supplied copybook structure. The fields defined in it are used to describe the success or failure of execution of each embedded SQL.

It is included as EXEC SQL INCLUDE SQLCA

END-EXEC

Copyright 2004, Cognizant Academy, All Rights Reserved

52

DB2 The important fields in this are:


SQLCODE ? Return Code of the last executed SQL passed by DB2 to the application 0 ? Successful Execution +Ve ? Successful Execution, but with an exception -Ve ? Execution Failed Note: Move the SQLCODE into a formatted field to display.

SQLERRD

an array containing 6 rows used to diagnose error conditions .

SQLERRD(3) -> no of rows inserted, deleted or updated by the SQL SQLERRD(5) -> gives column position of syntax error in a dynamic SQL

SQLWARN0 Contains W if any other SQLWARN* (1 thru A) have W.

SQLSTATE

- This is similar to SQLCODE. It has a 2 char Class code denoting the error type and a 3 Char subclass Code denoting the exact error in that error type.
A group of SQLCODES is associated to a single SQLSTATE .

The return code can be checked after every SQL and action taken depending on the requirement.

Null-Indicator Variables
Null indicator variables are used to handle nullable DB2 columns/fields in the application program. When the value in a column is not NULL, the host variable will contain the value of the column. The Null-indicator variable indicates the null status.
?? A positive or 0 implies column is not null. ?? A negative number indicates that the column has been set to null. ?? 2 implies data conversion error

Null indicator variables are used with the host variables in the following situations:
?? SET clause of UPDATE statement ?? VALUES clause of INSERT statement ?? INTO clause of the SELECT or FETCH statement

E.g.: EXEC SQL SELECT EMPNO, SALARY INTO: EMPNO, : SALARY: SALARY-IND FROM EMP WHERE EMPNO = 000100 END-EXEC.

Copyright 2004, Cognizant Academy, All Rights Reserved

53

DB2
Null Indicators are defined as PIC S9(4) COMP. If you fail to code Null indicator variable for a column that can return NULL, a SQLCODE of 305 is returned.

Cursors
COBOL operates on one row at a time while SQL operates on a set at a time. Cursors are used to handle this impedance mismatch. DB2 application programs use Cursors to navigate through a set of rows returned by an embedded SQL SELECT statement. A cursor can be likened to a pointer. We first DECLARE the cursor and define an SQL statement for that cursor. The cursor is opened, rows are fetched from the cursor one at a time and then the cursor is closed. The four operations performed on a Cursor are: DECLARE: Defines the cursor, gives it a name unique to the program in which it is embedded and assigns an SQL statement to the cursor name. This statement does not execute the SQL. This is generally written in the Working-Storage Section. Example: EXEC SQL DECLARE EMPCUR CURSOR FOR SELECT Empno, Empname, Dept, Job FROM EMP WHERE Dept = D11 FOR UPDATE OF Job END-EXEC. OPEN: Readies the cursor for row retrieval. OPEN is an executable statement. It reads he SQL search fields, executes the SQL statement and sometimes builds the results table. It does not assign values to the host variables. E.g.: EXEC SQL OPEN EMPCUR END-EXEC.

FETCH: Returns data from the results table one row at a time and assigns the values to specified host variables. If the results table is not built at the cursor OPEN time, it is built FETCH by FETCH. Example: EXEC SQL FETCH EMPCUR Copyright 2004, Cognizant Academy, All Rights Reserved

54

DB2
INTO: Empno,: Empname, :Dept, :Job END-EXEC. When you reach the end of a result set, the FETCH statement would return an SQLCODE of +100. CLOSE: Releases all resources used by the cursor. Example: EXEC SQL CLOSE EMPCUR END-EXEC.

Update/Delete using Cursor


Cursor can be used for modifying data using FOR UPDATE OF clause.
?? This helps in ensuring Data Integrity. ?? This helps in locking the data page when the fetch happens and ensures no other

updates happen. FOR UPDATE OF clause must contain all the columns that are included in the SET clause. The WHERE CURRENT OF clause must be used; else all the rows in the table will be updated. Rows can be deleted in a similar way. Example: EXEC SQL UPDATE EMP SET Job =: New-job WHERE CURRENT OF EMPCUR END-EXEC EXEC SQL DELETE FROM EMP WHERE CURRENT OF EMPCUR END-EXEC

Cursor update cannot be used if SELECT contains


?? ORDER BY ?? DISTINCT ?? GROUP BY ?? JOIN ?? UNION ?? Aggregate Function

Copyright 2004, Cognizant Academy, All Rights Reserved

55

DB2
Note: SQL has a error trapping statement WHENEVER When WHENEVER is used it applies to all the subsequent SQLs in that application. It can be used in 3 cases EXEC SQL WHENEVER NOT FOUND (* Not Found) CONTINUE WHENEVER SQLWARNING (* +Ve Sqlcode But Not +100 Or Sqlwarn0 = 0) GO TO WARNING-PARA WHENEVER SQLWARNING (* -Ve Sqlcode) GO TO WARNING-PARA END-EXEC Use of WHENEVER is not recommended.

Commit
COMMIT is the DB2 statement that saves the updates made to DB2 tables since the start of the program or the last COMMIT. It does so by physically applying the all the changes to the DB2 Log. (By default the work gets committed when the program ends.) When a program abends, the changes are rolled back to the last COMMIT/SYNC point. An explicit COMMIT is coded for the following reasons:
?? When a program fails all changes since the previous save point are backed out. ?? A resubmit of a failing program causes reprocessing of all records. ?? Repeatable Read page lock will lock the Tablespace and page until a COMMIT is

issued. Commit should always be used with caution as they affect performance. Cursors are implicitly closed when a COMMIT is issued (or when the program ends). But if the cursor is declared with WITH HOLD option, the result set is retained after issuing a COMMIT. This way we can continue to process the cursor from where we left. Otherwise the cursor will have to opened and repositioned.

When is a commit issued: A unit of work is a portion of processing that gives a logical completion and helps in achieving data integrity. Issuing a DB2 COMMIT saves the Updates done during a unit of work. For Example, suppose we have an application that involved update of 2 tables that are related to each other. And suppose the update of table is COMMIT-ed and the program abends before COMMITing the UPDATE to the other. The data in the 2 tables will no longer be synchronous. To Achieve data integrity, we must issue a COMMIT only when the processing reaches a logical end. Copyright 2004, Cognizant Academy, All Rights Reserved

56

DB2 Checkpoint-Restart Logic:


Application Programs which process large volumes of data and those that involve modification of DB2 Tables need to incorporate Restart Logic when a system error occurs. This is to help in continuing the processing from the record next to the last successfully processed row.
?? Create a DB2 table (Checkpoint table) that will have

o o o o o o

Pgm_name Job_name Commit_Frequency No_of_Commits Checkpoint_Key Checkpoint_Time

The Unique key will be Pgm_Name, Job Name Declare 2 cursors both with ORDER BY for the columns that form the unique index for the table. One cursor will be used to do normal processing. The other cursor while restarting the application is used to reposition at the record following the last saved record. This is done using additional predicates like Where Key > Last_Key For every row that is fetched, processing is done and tables are updated. Then based on elapsed time since last commit or commit frequency, etc, COMMIT is issued. Before every COMMIT is issued, the Checkpoint table is updated with the Current key for which processing is complete and the current timestamp. If the program is restarted, it reads the key in the Checkpoint table, uses that in 2nd cursor to reposition and then continues processing. After the processing is complete for all the rows, the Checkpoint table keys are set to default values. If File inputs are used for processing, then we need to reposition the input record by saving the read-count in the Checkpoint table. And upon restart perform read in a loop till the count is > the read-count. Or else is the file is sorted on the same key that is stored in the Checkpoint table, we can reposition to the next key. If there are File outputs, they need to be have a disp=Mod in the jcl to continue appending the records.

Pre-compilation
DB2 programs must be parsed and modified before normal compilation. The Pre-compiler performs this. The functions performed by the Pre-compiler are: ?? Searches for and expands DB2 INCLUDE members. (All DB2 related INCLUDE

members must be placed inside EXEC SQL. END-EXEC for DB2 to recognize them.
?? Searches for SQL statements in the body of the programs source code. ?? Comments out all the Embedded SQL Text and for every executable SQL, a CALL is

added to the DB2 runtime interface module DSNHLI along with the necessary parameters. Copyright 2004, Cognizant Academy, All Rights Reserved

57

DB2
?? Extracts all the SQL statements and places them in Database Request Module ?? DBRM ?? Places a unique timestamp token in the Modified source and DBRM ?? Reports the success or failure of the Pre-compile process.

DB2 need not be operational at the time of pre-compilation. DSNHPC is the pre-compiler program.

Compilation and Link


?? Modified Pre-compiler COBOL output is compiled ?? Compiled source is Link edited to an executable load module ?? Appropriate DB2 host language interface module should also be included in the link

edit step (i.e. DSNALI)


?? DB2 need not be operational at the time of compilation and link-editing

Bind
?? Bind Command is a type of compiler for SQL statements ?? It reads the SQL statements from the DBRM and produces a mechanism to access

data (access path) in an efficient manner, as directed by the SQL statements being bound
?? Checks syntax, checks for correctness of table & column definitions against the DB2

Catalog and performs authorization validation


?? The

output of this stage is the application plan that is executable with a corresponding load module.

There are two types of Binds: BIND PLAN: Accepts as input one or more DBRMs produced from previous DB2 precompilations, one or more packages produced from previous BIND PACKAGE commands, or a combination of DBRMs and package lists. The output of the BIND PLAN is an application plan containing executable logic representing optimized access paths to DB2 data. An application plan is executable only with the corresponding load module. BIND PACKAGE: Accepts as input a single DBRM and produces a single package containing the optimized access path logic. We should then bind packages into an application plan using the BIND PLAN command. The PLAN in this case contains a reference to the physical location of the package(s). A package is not executable and cannot be specified when a DB2 program is run. Advantages of Package
?? Reduced Bind Time Suppose a plan has more than one package bound to it. If

changes are made only to one DBRM. We only need to BIND Package for that DBRM and put in the same collection that is associated to the plan. So no need to Bind Plan again. Copyright 2004, Cognizant Academy, All Rights Reserved

58

DB2
?? With the use of Bind at Package level, the isolation and release parameters are

specified at the DBRM level, instead of the plan level.


?? Packages can be versioned and maintained. That is multiple packages can exist with

the same name in the same collection and in turn bound to a single plan. At run time, depending on the CONTOKEN of the load, the corresponding package is picked and executed. By Default, DB2 uses Timestamp as version identifier.
?? Provides for remote data access (in version DB2 V2.3 or higher)

Following DB2 tables have important details about the Plan/Package:


?? SYSDBRM has information on every DBRM that is bound into a package or a plan. ?? SYSSTMT has all the SQL statements of a DBRM that are bound into a plan. ?? SYSPACKSTMT has all the SQL statements of a DBRM that are bound into a

package. During BIND PLAN, the following DB2 Catalog tables are read:
?? SYSCOLDIST ?? SYSCOLDISTSTATS ?? SYSCOLSTATS ?? SYSCOLUMNS ?? SYSINDEXES ?? SYSINDEXSTATS ?? SYSPLAN ?? SYSPLANAUTH ?? SYSTABLES ?? SYSTABLESPACE ?? SYSTABSTATS ?? SYSUSERAUTH

? SYSPACKAGE ? SYSPACKAUTH

And information about the plan is stored in the following DB2 tables:
?? SYSDBRM ?? SYSPACKAUTH ?? SYSPACKLIST ?? SYSPLAN ?? SYSPLANAUTH ?? SYSPLANDEP ?? SYSPLSYSTE ?? SYSSTMT ?? SYSTABAUTH

? SYSPACKAGE ? SYSPACKAUTH ? SYSPACKDEP ? SYSPKSYSTEM ? SYSPACKSTMT

During Bind Package, the package is associated with a specific collection id.

Copyright 2004, Cognizant Academy, All Rights Reserved

59

DB2
//BIND EXEC PGM=IKJEFT01,COND=(5,LT)

//STEPLIB DD DISP=SHR,DSN=DSN710.SDSNLOAD //DBRMLIB DD DISP=OLD,DSN=FDR4378.BABU.FILES //SYSPRINT DD SYSOUT=* //SYSTSPRT DD SYSOUT=* //SYSUDUMP DD SYSOUT=* //SYSTSIN DD * DSN S(DSN) BIND PLAN(FDRPLN01) QUALIFIER(ID) MEMBER(DBRM1,DBRM2,.) PKLIST(COL1.PACKAGE1,COL2.*) ACTION(REPLACE) RETAIN VALIDATE(BIND)ACQUIRE(USE) RELEASE(COMMIT) ISOLATION(CS) DEGREE(ANY) EXPLAIN(NO) -

/*

What is Collection?
It is a logical grouping of packages. During Bind Plan, we specify the DBRMs that are directly bound to the plan and we also specify the packages that are bound to the plan. The packages are specified as collection_id.Package or collection_id.* to refer to all the packages in that collection. Advantage of using Collection:
?? The same DBRM can be bound into different packages that are associated to

different collection ids and using different qualifiers during BIND. And both the collections are used in the BIND PLAN. At run time, the same application can be made to access different sets of DB2 objects by using SET CURRENT PACKAGESET = COLLECTION ID
?? Logically related DB2 programs packages are grouped into the same collection.

Copyright 2004, Cognizant Academy, All Rights Reserved

60

DB2 Bind Parameters


ISOLATION (CS)
?? Specifies the mode of page locking implemented by the program as it runs (isolation

level).
?? DB2 implements Page and Row level locking. The different Isolation Levels are:

o o o o

Cursor Stability (CS): Releases Read-only page lock as soon as another page is accessed. Repeatable Read (RR): All page locks are held until released by a COMMIT. Read Stability (RS): Retrieved row or page is locked until the end of the unit of work. No other program can modify the data but new rows can be inserted. Uncommitted Read (UR): Read without acquiring locks. Data as it is being change is visible. Advised only for Read-only purposes.

ACQUIRE (USE) & RELEASE (COMMIT) Specifies when to Acquire and Release Tablespace locks. Parameters used are:
?? USE: Table space locks are taken when Tablespace is accessed. ?? ALLOCATE: Locks are taken when the plan is first allocated. ?? COMMIT: Locks are released at commit or rollback time. ?? DEALLOCATE: All locks are held until the plan finishes and is de-allocated

VALIDATE (BIND) Specifies validation strategy. A validation strategy refers to the method of checking for the existence and validity of DB2 tables and DB2 access authorization. Parameters allowed are
?? BIND: Bind fails for invalid access authority. ?? RUN: Validated during each execution. Degrades performance. ?? FLAG (I) BIND command returns all information, warning, error, and completion

messages. DEGREE (ANY) When DEGREE (ANY) is specified, DB2 attempts to execute queries in parallel engines whenever possible. Parallelisms considered during optimization are:
?? I/O: multiple read engines ?? CPU: multiple processor and read engines ?? SYSPLEX: multiple data sharing subsystems

EXPLAIN (YES) This allows proper monitoring of the production access path selection made by DB2. ACTION (REPLACE) ADD: Indicates it is a new plan REPLACE: Replaces an old plan

Copyright 2004, Cognizant Academy, All Rights Reserved

61

DB2 Execution
A DB2 Program has 2 components used in execution one is load module and the other is application plan.
?? The PLAN contains optimized access path for the SQLs in the program. ?? The link-edited module contains the machine code for the COBOL statements. ?? The link-edited module is tied forever with the DBRM by the timestamp. The two have

to be produced by the same pre-compile. At execution time the timestamp is verified for compatibility and a SQLCODE = 818 is issued when they do not match. DB2 programs can be executed in 4 ways:
?? Batch TSO ?? Call attach ?? CICS ?? IMS

Running a DB2 program in TSO Batch


?? PGM=IKJEFT01 ?? SYSTSIN DD * ?? DSN SYSTEM (DSN) ?? RUN PROGRAM (program name)

?? PLAN (plan name) ?? LIB ( load library)

END Sample JCL for Program Preparation Steps //COMPBAT JOB (ISAT),'COMPILE', // // // // //* /*JOBPARM PROCLIB=PROC20 //* //********************************************************* //* DB2 PRECOMPILE STEP FOR COBOL - BATCH //********************************************************* //* //STEP0001 EXEC PGM=DSNHPC, // // //* Copyright 2004, Cognizant Academy, All Rights Reserved REGION=4M, PARM='HOST(COB2),APOST,APOSTSQL' CLASS=2,MSGCLASS=X,REGION=4M, MBR=XXXXXXXX, FLEVEL=APPL.ID, **MEMBER NAME **LIBRARY PREFIX

SOURCE=APPL.ID.SOURCE **SOURCE DATASET

62

DB2
//STEPLIB DD DISP=SHR,DSN=DSN610.T00.SDSNLOAD //* //SYSLIB DD DISP=SHR,DSN=&FLEVEL..INCLUDE // //* //SYSPRINT DD SYSOUT=* //SYSTERM DD SYSOUT=* //SYSUDUMP DD SYSOUT=* //* //SYSUT1 DD UNIT=SYSDA,SPACE=(CYL,(1,2)) //SYSUT2 DD UNIT=SYSDA,SPACE=(CYL,(1,2)) //SYSUT3 DD UNIT=SYSDA,SPACE=(CYL,(1,2)) //SYSUT4 DD UNIT=SYSDA,SPACE=(CYL,(1,2)) //SYSUT5 DD UNIT=SYSDA,SPACE=(CYL,(1,2)) //* //DBRMLIB DD DISP=SHR,DSN=&FLEVEL..DBRMLIB(&MBR) //* //SYSIN //* //SYSCIN DD DSN=&&SRCOUT, // // DISP=(NEW,PASS), UNIT=SYSDA,SPACE=(CYL,(1,2)) DD DISP=SHR,DSN=&SOURCE(&MBR) DD DISP=SHR,DSN=&FLEVEL..DCLGENLIB

//********************************************************* //* COBOL COMPILE //********************************************************* //* //STEP0002 EXEC PGM=IGYCRCTL, // // //* //STEPLIB DD DISP=SHR,DSN=SYS1.COB2COMP //* //SYSLIB DD DISP=SHR,DSN=CICSTS.CICS.SDFHCOB // //* //SYSPRINT DD SYSOUT=* //* //SYSUT1 DD UNIT=SYSDA,SPACE=(CYL,(1,2)) //SYSUT2 DD UNIT=SYSDA,SPACE=(CYL,(1,2)) //SYSUT3 DD UNIT=SYSDA,SPACE=(CYL,(1,2)) //SYSUT4 DD UNIT=SYSDA,SPACE=(CYL,(1,2)) //SYSUT5 DD UNIT=SYSDA,SPACE=(CYL,(1,2)) Copyright 2004, Cognizant Academy, All Rights Reserved DD DISP=SHR,DSN=&FLEVEL..COPYLIB ** COPY/INCLUDE DATASET REGION=4M, PARM=''

63

DB2
//SYSUT6 DD UNIT=SYSDA,SPACE=(CYL,(1,2)) //SYSUT7 DD UNIT=SYSDA,SPACE=(CYL,(1,2)) //* //SYSIN // //* //SYSLIN DD DSN=&&OBJECT, // // //* //********************************************************* //* LINK EDIT THE BATCH PROGRAM FOR DB2 //********************************************************* //STEP0003 EXEC PGM=IEWL, // // //* //SYSLIB DD DISP=SHR,DSN=DSN610.T00.SDSNLOAD // // // // // // //* //SYSPRINT DD SYSOUT=* //* //SYSUT1 DD UNIT=SYSDA,SPACE=(CYL,(1,2)) //* //SYSIN // //* //SYSLMOD DD DISP=SHR,DSN=&FELEVL..BATCH.LOADLIB(&MBR) //* //SYSLIN DD * INCLUDE SYSIN NAME &MEMBER(R) //* //********************************************************* //* BIND PLAN FOR MODULE //********************************************************* //STEP0004 EXEC PGM=IKJEFT01, Copyright 2004, Cognizant Academy, All Rights Reserved DD DSN=&&OBJECT, DISP=(OLD,PASS) DD DISP=SHR,DSN=CEE.SCEELKED DD DISP=SHR,DSN=GDDM.SADMMOD DD DISP=SHR,DSN=QMFHPO.V6R1M0.SRAALOAD DD DISP=SHR,DSN=PCSQL.V2R0M0.SPLOAD DD DISP=SHR,DSN=DCL.V1R5M10.LOADLIB DD DISP=SHR,DSN=&FLEVEL..BATCH.LOADLIB REGION=4M, PARM='LIST,LET,MAP,XREF,AMODE=31,RMODE=ANY,RENT' DISP=(NEW,PASS), UNIT=SYSDA,SPACE=(CYL,(1,3)) DD DSN=&&SRCOUT, DISP=(OLD,DELETE)

64

DB2
// REGION=4M //* //STEPLIB DD DISP=SHR,DSN=DSN610.T00.SDSNLOAD //* //DBRMLIB DD DISP=SHR,DSN=&FLEVEL..DBRMLIB //* //SYSUDUMP DD SYSOUT=* //SYSTSPRT DD SYSOUT=* //SYSPRINT DD SYSOUT=* //* //SYSTSIN DD * DSN SYSTEM(DSN) BIND PLAN(&MEMBER.) MEMBER(&MEMBER.) ACTION(REPLACE) RETAIN VALIDATE(BIND) ACQUIRE(USE) RELEASE(COMMIT) ISOLATION(CS) DEGREE(ANY) EXPLAIN(YES) //*

Application Programming Guidelines


?? Code modular DB2 programs and make them as small as possible ?? Use unqualified SQL statements; this enables movement from one environment to

another (Test to Production)


?? Never use Select* in an embedded SQL program ?? Use Joins rather than Subqueries ?? Use WHERE clause wherever possible and filter out data ?? Use cursors when fetching multiple rows, though they add overheads ?? Use FOR UPDATE OF clause for UPDATE or DELETE with cursor - this ensures

data integrity.
?? Use INSERTs minimally; use LOAD utility instead of INSERT, if the inserts are not

application dependent

Copyright 2004, Cognizant Academy, All Rights Reserved

65

DB2

Chapter 5:DB2 Utilities


Learning Objectives
The chapter shall achieve the following objectives:
?? Learning of different DB2 supplied utility functions

Data Consistency Utilities


CHECK Utility checks the integrity of DB2 data structures
?? Checks referential Integrity between 2 tables and resolves the referential constraint

violations by moving the erroneous rows to exception tables.


?? Checks the status of Check Constraints ?? Checks DB2 Indexes for consistency of index data and the corresponding table data

No corresponding row for a given index value / No corresponding index value for a table row / For a matching RID, the value in the index and the table dont match.
?? Can delete invalid rows and copy them to a exception table ?? Use

CHECK DATA when loading a table without specifying the ENFORCE CONSTRAINTS option or after the partial recovery of Table spaces in a referential set.

REPAIR Utility
?? Used to Reset Pending flags that are unnecessary or are set erroneously. ?? Used to sync up the information abt a DB2 database which is stored in the

SYSDATABASE table and the definition of the DBD in the DB2 directory.

REPORT Utility
?? Reports the names of TS and Tables which are tied together by referential Integrity

COPY Utility
?? Used to create full or partial image copy of a full TS or a Partition in a TS. ?? Full Copy copies all the data in the TS or partition. ?? Incremental copy copies only those pages that have been modified since the last

image-copy that was taken.


?? For every run, a row is inserted in SYSIBM.SYSCOPY table with information on the

image copy, DSNAME, date and time of copy. The image copy datasets are useful for TS recovery.

MERGECOPY Utility
?? Merges multiple image copy datasets into a single image copy dataset

Copyright 2004, Cognizant Academy, All Rights Reserved

66

DB2 QUIESCE Utility


?? It is used to record a point of consistency for related application or system TS. ?? It ensures that all TS in the scope are referentially intact.

RECOVER Utility
?? RECOVER TABLESPACE Utility restores Tablespace to a current or previous state.

First it checks what image copies are available for that TS and checks the DB2 Logs for interim changes. T hen applies the image copy data and the log data to the TS being recovered.
?? Data can be recovered for single pages, pages that contain I/O errors, a single

partition or an entire Tablespace.


?? RECOVER INDEX is used to recreate indexes from current data. Indexes are always

recovered from the actual table data on which index is created and not from image copy or log data.

DB2 Logs DB2 keeps a log of all changes made to TS. All updates are recorded in DB2 active log. When the active log becomes full, it creates an archive log. There could be multiple archive logs created during application processing. All the info is stored in the DB2 Directorys SYSIBM.SYSLGRNG table. LOAD Utility is used to do bulk inserts into table.
?? It can add or replace existing data. (LOAD DATA REPLACE or LOAD DATA

RESUME (S))
?? If a job terminates in any phase of LOAD REPLACE the utility has to be terminated

and rerun
?? If a job terminates in any phase other than UTILINIT (which sets up and initializes the

LOAD utility), the Tablespace must be first restored using the full RECOVER, if LOG NO option of the LOAD was mentioned.. After the Tablespace is restored, the error is to be corrected, the utility terminated and the job rerun. RUNSTATS This utility collects statistical information for Tables, Tablespaces, Partitions, Indexes and Columns in tables .
?? It can be used to Update all the information in the relevant catalog tables or can be

used simply for generating all the information in the form of a report.
?? It is this statistical data that is used by the DB2 optimizer to arrive at an optimal

access path.
?? It is good to run RUNSTATS after every LOAD. After running RUNSTATS, the plans

and packages with static SQL have to be rebound to have the access paths based on the recent statistics.
?? It can be used on specific SQL queries without updating the current usable statistics

Copyright 2004, Cognizant Academy, All Rights Reserved

67

DB2

REORG Used to reorganize DB2 Tablespaces and Indexes, thereby improving the efficiency of access to those objects. REORG reclusters data, resets free space to the amount specified in CREATE DDL.

REORG Job Streams


The total REORG schedule should include
?? A RUNSTATS job or step: to record current Tablespace and index statistics to DB

catalog
?? Two copy steps for each Tablespace being reorganized; so that data is recoverable.

The second copy job is required after the REORG if it was performed with a LOG NO option
?? After a REORG is run with LOG NO option, DB2 turns on the copy pending status

flag for Tablespaces specified in the REORG.


?? When LOG NO parameter is specified it is better to take a image copy of the

Tablespace being reorganized immediately after REORG


?? A REBIND job for all plans using tables in any of the Tablespaces being organized

EXPLAIN
?? This feature can be detail the access paths chosen by the DB2 optimizer for SQL

statements
?? Used for performance monitoring ?? When EXPLAIN is requested the access paths that the DB2 chooses are put in

coded format into the table PLAN_TABLE, which is created in the default database
?? To EXPLAIN a single SQL statement precede that SQL stmt with the EXPLAIN

Command EXPALIN ALL SET QUERYNO = integer FOR SQL stmt


?? The other method is specifying EXPLAIN YES with the Bind command ?? Then PLAN_TABLE is to be queried to get the required information. ?? The information provided include the type of access of particular tables used in the

SQL or Package or Plan, the order in which the tables or joined in a JOIN, whether SORT is required and so on
?? Since the EXPLAIN results are dependent on the DB catalog, it is better to run

RUNSTATS before running a EXPLAIN

DB2 Security, Catalog Tables and Optimizer


Security

Copyright 2004, Cognizant Academy, All Rights Reserved

68

DB2
Locking Services: These are provided by an MVS subsystem called the IMS Resource Lock Manager (IRLM). It is used to control concurrent access DB2 data, regardless of whether IMS is present in a system or not.

Locking Hierarchy
Segmented Tablespace Table

Row

Page

?? The above is based on Transaction Processing - the system component that provides

this is A TRANSACTION MANAGER


?? COMMIT & ROLLBACK are key methods of implementing locking schemes

Explicit Locking Facilities:


?? The SQL statement LOCK TABLE ?? The ISOLATION parameter on the BIND PACKAGE command - the two possible

values are RR (Repeatable Read) & CS(Cursor Stability) Page or Row level locks
?? The tablespace LOCKSIZE parameter - physically DB2 locks data in terms of pages

or tables or tablespaces. This parameter is specified in CREATE or ALTER Tablespace option LOCKSIZE. The options are Tablespace, Table, Page or Any
?? The ACQUIRE/RELEASE parameters on the BIND PLAN command specify when

table locks (which are implicitly acquired by DB2) are to be acquired and released.
?? Types: ACQUIRE USE & ACQUIRE ALLOCATE ?? RELEASE USE & RELEASE ALLOCATE

Catalog Tables and DB2 Directory:


?? Repository for all DB2 objects - contains 43 tables ?? Each table maintains data about an aspect of the DB2 environment

Copyright 2004, Cognizant Academy, All Rights Reserved

69

DB2
?? The data refers to info about tablespaces, tables, indexes, privileges, on utilities run

on DB2 and so on. E.g. : SYSIBM.SYSTABLES, SYSINDEXES/SYSCOLUMNS ......


?? When standard DB2 SQL is used, the DB2 catalog is either accessed or updated.

E.g. When a CREATE TABLE stmt is issued the catalog tables SYSIBM.SYSTABLES, SYSIBM.SYSCOLUMNS & SYSIBM.SYSFIELDS are updated.
?? However the DB2 catalog is semi active only. This is because updates to number of

rows, the physical order of the rows for a set of keys and the like are updated only after running a RUNSTATS utility
?? DB2 catalog is integrated - DB2 catalog and DB2 DBMS are inherently bound

together
?? It is nonsubvertible

- DB2 catalog cannot be updated behind DB2s back. I.e. if a table of 10 columns is created, it is not possible to go and change the number of columns directly on the catalog to 15. It has to be done using the standard SQL statements for dropping and recreating the table

Important Catalog Tables are listed below:


?? SYSCHECKS - One row for each Check Constraint ?? SYSCOLUMNS One row for every column in a table and view defined . ?? SYSDATABASE - One row for each database ?? SYSDBRM one row for each dbrm bound into DB2 plans. ?? SYSFOREIGNKEYS contains information about all columns participating in foreign

keys
?? SYSINDEXES one row for every index ?? SYSPACKAGE contains one row for each package ?? SYSPACKAUTH contains the privileges held by DB2 users on packages. ?? SYSPACKDEP

cross-reference of DB2 objects on which each package is

dependent
?? SYSPACKLIST contains the list of DB2 packages that have been bound into

Application Plans.
?? SYSPACKSTMT contains SQL statements for every DB2 package. ?? SYSPLAN contains one row for each plan. ?? SYSPLANAUTH contains the plan (bind and execute ) privileges held by DB2. ?? SYSPLANDEP crossref of db2 objects used by each plan. ?? SYSRELS contains details of referential integrity constraints the constraint name,

parent table, child table. Deleterule,etc


?? SYSSTMT contains SQL statements for every plan. ?? SYSSTOGROUP ?? SYSSYNONYMS ?? SYSTABAUTH contains information on the table privileges held by DB2 users. ?? SYSTABLEPART contains information on tablespace partitions ?? SYSTABLES - contains one row for each Table

Copyright 2004, Cognizant Academy, All Rights Reserved

70

DB2
?? SYSTABLESPACE- contains one row for each Tablespace ?? SYSVIEWDEP contains a cross-reference of DB2 objects on which each view

depends.
?? SYSVIEWS contains one row for each View

Optimizer
?? Analyzes the SQL statements and determines the most efficient way to access data -

gives Physical data independence


?? It evaluates the following factors: CPU cost, I/O cost, DB2 catalog statistics & the

SQL statement
?? It estimates CPU time, cost involved in applying predicates, traversing pages and

sorting
?? It estimates the cost of physically retrieving and writing the data ?? The information pertaining to the state of the tables that will be accessed by the SQL

statements are provided by the Catalog

Performance Tuning
?? The performance of an application can be monitored and enhanced in the application, as well

as database level
?? ?? In application side the SQLs can be tuned to make them more efficient, and avoid

redundancy
?? It is better to structure the SQLs so that they perform only the necessary operations ?? On the database side, the major enhancements can be done to the definitions of tables,

indexes & the distribution of tablespace and Indexspace.

Copyright 2004, Cognizant Academy, All Rights Reserved

71

DB2

REFERENCES
WEBSITES
http://www.tutorgig.com/t/DB http://www-106.ibm.com/developerworks/db2/library/tutorials/iminer/iminer.html http://www.techtutorials.info/datadb2.html

BOOKS
?? DB2 Developers Guide, Craig.S.Mullins

Copyright 2004, Cognizant Academy, All Rights Reserved

72

DB2

STUDENT NOTES:

Copyright 2004, Cognizant Academy, All Rights Reserved

73

Вам также может понравиться