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

DB2

DB2

DB2 HO VER 0.3 1


DB2

Table of Contents

INTRODUCTION TO DB2...........................................................................................................................5
1.1 Data Base Management System.............................................................................................................5
1.1.1) Relational Data Base Management System...................................................................................5
1.2) D B 2.....................................................................................................................................................5
1.2.1) Structured Query Language (SQL)................................................................................................5
1.3) How does a COBOL program use DB2 services..................................................................................6
1.3.1) Host Variables................................................................................................................................6
1.3.2) SQL Communication Area.............................................................................................................6
1.3.3) SQL statements..............................................................................................................................6
1.4) Handling a request.................................................................................................................................6
SYSTEM STRUCTURE................................................................................................................................8
2.1) Major Components................................................................................................................................8
2.1.1) System Services.............................................................................................................................8
2.1.2) Locking Services............................................................................................................................8
2.1.3) Database Services...........................................................................................................................8
2.1.3.1 ) Precompiler............................................................................................................................9
2.1.3.2) Bind.........................................................................................................................................9
2.1.3.3) Runtime Supervisor.................................................................................................................9
2.1.3.4) Data Manager..........................................................................................................................9
2.1.3.5) Buffer Manager.......................................................................................................................9
2.1.4) Distributed Data Facility................................................................................................................9
2.2) Detailed Control Flow.........................................................................................................................10
2.2.1) Syntax Checking..........................................................................................................................11
2.2.2 ) Optimization................................................................................................................................11
2.2.3) Package Generation......................................................................................................................11
2.2.4.) Authorization checking...............................................................................................................11
2.3) Packages Plans and Collections..........................................................................................................12
DATA TYPES AND OPERATORS...........................................................................................................13
3.1) Data Types..........................................................................................................................................13
3.1.1)Numeric data.................................................................................................................................13
3.1.2) String Data...................................................................................................................................13
3.1.3) Date/Time.....................................................................................................................................13
3.2) Operators and Expressions..................................................................................................................14
3.3) Scalar Functions..................................................................................................................................14
DB2 DATA STRUCTURES........................................................................................................................16
4.1) Introduction.........................................................................................................................................16
4.2) Database..............................................................................................................................................16
4.3 ) Table Spaces.......................................................................................................................................16
4.3.1 ) Simple Table Space.....................................................................................................................16
4.3.2) Partitioned Table Space................................................................................................................17
4.3.3) Segmented Table Space...............................................................................................................17
4.4) DB2 Stored Tables..............................................................................................................................17
4.5) Index....................................................................................................................................................18
4.6) Index Spaces........................................................................................................................................19
4.7) Storage Groups....................................................................................................................................19
4.8) Views...................................................................................................................................................19
4.9) Alias....................................................................................................................................................20
4.10) The hierarchy of DB2 objects...........................................................................................................20
INTEGRITY.................................................................................................................................................21
5.1) Introduction.........................................................................................................................................21
5.2) Primary key.........................................................................................................................................21
5.2.1) Definition.....................................................................................................................................21
5.3) Entity Integrity....................................................................................................................................22

DB2 HO VER 0.3 2


DB2

5.4) Foreign Keys.......................................................................................................................................22


5.4.1) Definition.....................................................................................................................................22
5.5) Referential Integrity............................................................................................................................22
5.6) DELETE rules.....................................................................................................................................22
STRUCTURED QUERY LANGUAGE.....................................................................................................24
6.1) Introduction.........................................................................................................................................24
6.2) Types of SQL......................................................................................................................................24
DATA DEFINITION LANGUAGE...........................................................................................................25
7.1) Introduction.........................................................................................................................................25
7.2) CREATE TABLE...............................................................................................................................25
7.2.1 ) CREATE TABLE Using LIKE...................................................................................................26
7.3 ) ALTER TABLE.................................................................................................................................26
7.4 ) DROP TABLE...................................................................................................................................26
7.6 ) INDEXES...........................................................................................................................................27
7.6.1 ) CREATE INDEX........................................................................................................................27
7.6.2 ) DROP INDEX.............................................................................................................................27
DATA MANIPULATION LANGUAGE...................................................................................................28
8.1 ) Introduction........................................................................................................................................28
8.2 ) SELECT.............................................................................................................................................28
8.2.1) Simple Retrieval...........................................................................................................................28
8.2.2) Qualified retrieval........................................................................................................................29
8.2.3 ) Retrieval with Ordering..........................................................................................................29
8.2.4 ) Retrieval using BETWEEN and IN............................................................................................29
8.2.5 )Retrieval using LIKE...................................................................................................................30
8.2.6) Retrieval involving NULL...........................................................................................................30
8.3 ) JOIN Queries......................................................................................................................................31
8.3.1 ) Simple Equijoin...............................................................................................................................31
8.3.3 ) Greater than Join.........................................................................................................................31
8.3.4 )Join query with additional conditions..........................................................................................31
8.3.5 ) Joining a table to itself................................................................................................................31
8.4 ) SUBQUERIES...................................................................................................................................32
8.4.1 ) Simple Subquery.........................................................................................................................32
8.4.2) Correlated Subquery.....................................................................................................................32
8.4.3 ) Scalar Comparison Operator.......................................................................................................33
8.5 ) The Existential Qualifier....................................................................................................................33
8.6 ) Quantified Comparisons.....................................................................................................................33
8.7 ) Column Functions..............................................................................................................................34
8.8 ) GROUP BY........................................................................................................................................34
8.9 ) Use of HAVING................................................................................................................................34
8.10 ) UNION.............................................................................................................................................35
8.11 ) INSERT............................................................................................................................................35
8.12 ) UPDATE..........................................................................................................................................36
8.13) DELETE............................................................................................................................................36
THE CATALOG..........................................................................................................................................37
9.1 ) Introduction........................................................................................................................................37
9.2) SYSTABLES......................................................................................................................................37
9.3 ) SYSCOLUMNS.................................................................................................................................37
9.4 ) SYSINDEXES...................................................................................................................................37
9.5 ) QUERYING THE CATALOG..........................................................................................................37
9.6 ) ALIASES AND SYNONYMS..........................................................................................................38
VIEWS...........................................................................................................................................................39
10.1 ) Introduction......................................................................................................................................39
10.2) VIEW DEFINITION.........................................................................................................................39
10.3) RETRIEVAL Operations..................................................................................................................39
10.4) UPDATE Operations........................................................................................................................40
SECURITY AND AUTHORIZATION......................................................................................................41

DB2 HO VER 0.3 3


DB2

11.1 ) Introduction......................................................................................................................................41
11.3 ) GRANT AND REVOKE.................................................................................................................41
11.4 ) The GRANT OPTION.....................................................................................................................41
EMBEDDED SQL........................................................................................................................................42
12.1 ) Introduction......................................................................................................................................42
12.2 ) Preliminaries....................................................................................................................................42
12.3 ) Operations Involving CURSORS....................................................................................................43
12.3.1 )DECLARE.................................................................................................................................44
12.3.2 )OPEN.........................................................................................................................................44
12.3.3)FECTCH.....................................................................................................................................44
12.3.4)CLOSE........................................................................................................................................44
12.3.5)WITH HOLD clause...................................................................................................................45
TRANSACTION PROCESSING................................................................................................................46
13.1) Introduction.......................................................................................................................................46
13.2) COMMIT and ROLLBACK.............................................................................................................46
13.3) Three CONCURRENCY PROBLEMS............................................................................................47
13.3.1)The LOST UPDATE problem....................................................................................................47
13.3.2)The UNCOMMITED DEPENDENCY problem........................................................................47
13.3.3)The INCONSISTANT ANALYSIS problem.............................................................................48
13.4) Solution.............................................................................................................................................48
13.5) Locking Facilities..............................................................................................................................49
13.5.1) LOCK TABLE...........................................................................................................................49
13.5.2) The ISOLATION parameter......................................................................................................49
13.5.2.1)CURSOR STABILITY........................................................................................................49
13.5.2.2) REPETABLE READ..........................................................................................................49
13.5.3)LOCK SIZE................................................................................................................................50
13.5.4) The ACQUIRE/RELEASE parameters......................................................................................50
13.6) DEADLOCK.....................................................................................................................................50
DYANAMIC SQL........................................................................................................................................51
14.1)Introduction........................................................................................................................................51
14.2) PREPARE/EXECUTE......................................................................................................................51
14.3) EXECUTE IMMEDIATE.................................................................................................................52
ADMINISTRATION FACILITIES............................................................................................................53
15.1) Introduction.......................................................................................................................................53
15.2) DB2 INTERACTIVE INTERFACE.................................................................................................53
15.2.1) SPUFI.........................................................................................................................................54
15.2.2) DCLGEN....................................................................................................................................54
15.2.3)Program Preparation....................................................................................................................54
15.2.4)Precompile...................................................................................................................................54
15.2.5) Bind / Rebind / Free...................................................................................................................54
15.2.5) RUN...........................................................................................................................................55
15.2.6) DB2 Commands.........................................................................................................................55
15.2.7)Utilities........................................................................................................................................55
15.2.8)Catalog Visibility........................................................................................................................55
15.2.9) DB2I Defaults............................................................................................................................55
15.2.10) EXIT.........................................................................................................................................55
15.3) EXPLAIN..........................................................................................................................................55
15.4) Database utilities...............................................................................................................................56

DB2 HO VER 0.3 4


DB2

INTRODUCTION TO DB2

1.1 Data Base Management System

A Data Base, which consists of some collection of persistent data that is used by the application
systems of some given enterprise. These are designed and managed to store large quantities of information.
A Data Base Management System (DBMS) is a software package that manages the data stored in
databases. Data base approach will help to maintain data independence, avoid redundancy, inconsistency
and also provide better security. Thus DBMS provide an environment that is both convenient and efficient
to use in retrieving and storing data base information.

1.1.1) Relational Data Base Management System

A Relational Data Base System presents all information in form of tables. Tables consist of rows
and columns. This concept is in close correspondence with mathematical concept of relations and hence the
name.

1.2) D B 2

DB2 an abbreviation for DataBase 2, is a Relational DataBase Management System(RDBMS) that


runs on IBM mainframe computers under MVS operating system. Prior to DB2 there was a hierarchic Data
Base Management System (DBMS) for MVS called IMS (Information Management System). DB2 is one
of the most successful DBMS for MVS.

1.2.1) Structured Query Language (SQL)

This is the language by which request to DB2 are made.DB2 supports SQL, which provides
facilities for application programming as well as for data base management. SQL is both ANSI and ISO
standard. In fact it is the language used to access all relational databases.
The statements, which make up SQL are commonly categorized in to Data Definition Language
(DDL), Data Manipulation Language (DML), and Control statements. DBA uses DDL for defining various
objects. Application programmers uses DML to work with DB2. Control statements are used to handle
authorization to various resources.

DB2 HO VER 0.3 5


DB2

1.3) How does a COBOL program use DB2 services

When DB2 is used through COBOL, SQL statements are to be included in the program. Following
are the three things that are to be included when using DB2 in COBOL programs Host variables, SQL
communication Area, and SQL statements.

1.3.1) Host Variables

These are used for retrieving and putting data into DB2 tables. Host variables have to be defined
in the program, which is used to receive the data DB2 returns and from which DB2 can get the data to
update tables. They are called host variables because they reside in the storage owned by host program.

1.3.2) SQL Communication Area

DB2 provides the feedback about the success of each operation by Storing information in SQLCA.
So in COBOL program SQLCA have to be included.

1.3.3) SQL statements

SQL statements actually does the data base work required by the program. SQL
statements can be embedded into a programming language. These SQL statements are not understood by C,
COBOL etc. So before compiling the program, a preliminary process (Precompiler) must pull out the SQL
statements.
1.4) Handling a request

DB2 HO VER 0.3 6


DB2

When a request to update the database comes to DB2 from the user. The application manager
passes the userid to DB2. DB2 will check for the authorization of the user. It maintains a catalog to see
whether the user is authorized. If not authorized DB2 will return a code indicating it has refused the request
due to unauthorized user id. There are multiple concurrent processing handled by DB2. To avoid a possible
confusion DB2 puts a lock on data. DB2 maintains a log which keeps record about everything that is done
to the data. DB2 always writes to the log before writing to the data after the successful updation it will
mark a COMMIT to the log. Since the update is completed DB2 releases the lock and the operation
completed successfully

DB2 HO VER 0.3 7


DB2

SYSTEM STRUCTURE
2.1) Major Components

There are four major components, each of which divides into a number of subcomponents. They
are
 The system service component
 The locking services
 The database services
 The distributed data facility component

2.1.1) System Services

The system services supports the system operations. This handles DB2 system related tasks
including controlling connections to other MVS subsystems, handling system startup, shutdown and
operator communications, managing system log, gathering system-wide statistics, performance auditing
and accounting informations etc.
The system logs are data sets used to record the information for recovering the user and system
data in the event of system failure. The logs are of two types; active log and archive log.

2.1.2) Locking Services

Locking services are provided by an IMS Resource Lock Manager (IRLM), which is a general-
purpose locking manager. This is used to control the concurrent access to DB2 data.

2.1.3) Database Services

This is used to retrieval and updation of database i.e. implements the functions of SQL. This
includes five subcomponents. They are:
 Precomipler
 Bind
 Runtime Supervisor
 Data Manager
 Buffer Manager

DB2 HO VER 0.3 8


DB2

2.1.3.1 ) Precompiler

This is a preprocessor for host programming languages. Precompiler analyses the host language
source module, stripping out the SQL statements and replace them by host language CALL statements. The
precompiler produces two output files. The first is intermediate source program, Which contains the
COBOL statements. The original SQL statements in the program will be commented out so that COBOL
compiler ignores them. Second file produced by precompiler called Data Base Request Module (DBRM).

2.1.3.2) Bind

This is used to bind a DBRM to produce a package and also it binds together a list of packages to
produce an application plan. The package can be thought as a set of internal control structures, representing
the compiled form of original SQL statements in the DBRM.
Collections are a set of logically related packages, which does not have a physical existence. All
the packages used in a given application are assigned to the same collection. Host language compiler,
which compiles the modified source code to produce the Object module for the host language.

2.1.3.3) Runtime Supervisor

This is resident in the main storage during the execution and it overseas the execution of job.
When the SQL statements are executed, control first goes to runtime supervisor, which uses the control
informations in the plan to request appropriate operations on the part of Data manager.

2.1.3.4) Data Manager

This is a very sophisticated access method. It performs the normal access method functions like
search, retrieval etc. It also invokes the other system components to invoke locking ,I/O operations etc.

2.1.3.5) Buffer Manager

This is a component responsible for transferring data between external storage and memory. It
uses several methods to optimize its performance so that amount of I/O can be reduced.

2.1.4) Distributed Data Facility


This component called DDF, which provide Distributed database support. It has to work with
other subsystems to attain this facility.

DB2 HO VER 0.3 9


DB2

2.2) Detailed Control Flow

This section will explain how to prepare and execute DB2 embedded application program. After preparing
the program with embedded DB2 statements it has to be precompiled first. This is because the host
language compiler does not understand the embedded DB2 statements. The precompiler replaces all SQL
statements with CALL statements. The SQL statements will be commented out. Precompiler uses SQL
statements to build a DBRM, which is stored in a partitioned dataset. DBRM contains edited form of SQL

DB2 HO VER 0.3 10


DB2

statements together with some additional informations. So the output of precompilation is modified source
code and DBRM.
Modified source code is compiled and linkedited in normal way by using the host language compiler.
Bind is really an optimizing compiler. It will convert SQL statements into optimized internal form. Its input
is DBRM and output is a package. The major functions performed by bind are

 Syntax checking

 Optimization

 Package generation

 Authorization checking

2.2.1) Syntax Checking

Bind examines the SQL statements for syntax errors.

2.2.2 ) Optimization

Bind includes an optimizer to choose for each SQL statement an optimal access strategy for
implementing that statement. For example when the user wants to access some data the access path is
selected by the optimizer. Bind will generate a code that is tightly bound to optimizer’s choice of path.

2.2.3) Package Generation

This is the actual process of building the package.

2.2.4.) Authorization checking

Bind checks for authorization. It check for whether the user is allowed to perform the operations
requested on DBRM and also whether allowed to assign packages applicable to packages collection.

Bind also performs the plan bind. The input of this process is a list of packages. Output is an
application plan, which is stored in DB2 directory. This also done some authorization checking such as
whether the owner is authorized to execute all application packages.
At the time of execution both load module (from modified source code) and application plan (from
DBRM) to be used. The load module is loaded to memory and it stars execution. When it reaches the first
call to DB2 language interface module it passes the control to runtime supervisor. The runtime supervisor

DB2 HO VER 0.3 11


DB2

retrieves the application plan from DB2 directory and loads it into memory. Then the control is passed to
Data manager, which performs the necessary operations on the data and passes the result back to the
program.

2.3) Packages Plans and Collections

Package is a compiled form of DBRM. Plan is a list of packages. Plan may consist of more than
one packages. So if a given DBRM has to be recompiled, the appropriate package has to be bind not the
entire plan. If multiple plans involve the same DBRM, that can be compiled once and the corresponding
package can be referenced multiple times instead of binding the DBRM each time.
Collections is a logical grouping of packages. It is even possible to add a new package to a plan
without binding it. This is by using the concept of collections. When a plan is bound the input can be a
collections. This is equivalent to adding all packages in that collection. Including packages in the collection
can be done after plan is bound. Whatever packages in the collection while plan is executed is considered to
be a part of the plan.

DB2 HO VER 0.3 12


DB2

DATA TYPES AND OPERATORS


3.1) Data Types

DB2 supports the following scalar data types

3.1.1)Numeric data

INTEGER Full word binary integer, 31 bits and sign


SMALLINT Half word binary integer, 15 bits and sign
DECIMAL(p,q) Packaged decimal with p digit and sign. Decimal
point at q digit from right
FLOAT(p) Floating point number

3.1.2) String Data

CHARACTER(n) Fixed length string of ‘n’ 8bit characters. Maximum


value of n is 254
VARCHAR(n) Varying length string up to ‘n’ 8bit characters Max
value of ‘n’ is 4K/32K
GRAPHIC(n) Fixed length string of ‘n’ 16bit characters Max
value of ‘n’ is 127
VARGRAPHIC(n) Varying length string upto ‘n’ 16bit characters. Max
value of ‘n’ is 24K/16K

3.1.3) Date/Time
DATE Eight unsigned packed decimal occupying 4 bytes
YYYYMMDD
TIME 6 unsigned packed decimal occupying 3 bytes
HHMMSS
TIMESTAMP Sequence of 20 unsigned packed decimal digits
YYYYMMDDHHMMSSNNNNNN

3.2) Operators and Expressions

DB2 provide a number of scalar operators that can be used in making scalar expressions.

DB2 HO VER 0.3 13


DB2

Numeric Operators DB2 supports numeric operators such as +,-,/,*


These can be used with date,time,timestamp etc
Comparisons =,>,<.<>,>=,<=, Even two dates can be compared

Concatenation || This is used to concatenate two character or two


graphic strings

A scalar expression consists of scalar operands to produce another scalar value. These can appear
in SQL statements with SELECT, HAVING, WHERE etc. There are six types of scalar expressions. They
are Numeric, Character, Graphic, date, time,and timestamp.
E.g. Numeric Expression
STATUS
WEIGHT = WEIGHT*23
E.g. Character string
PNAME
INITIALS || LASTNAME

3.3) Scalar Functions

Scalar functions applied to a single column or expressions and operate on single value. The result
will be transformed version of column or expression. These can be executed in the
SELECT,WHERE,HAVING etc.

CHAR Converts DB2 time,date,timestamp,decimal to character


DATE Converts a value to a DB2 date. It can be a positive integer,
timestamp etc.
DAY Returns day portion of DB2 timestamp
DAYS Converts DB2 timestamp into number of days since jan1
0001
DECIMAL Converts numeric value to a decimal
DIGITS Converts a number to a string of digits. Truncate - sign
FLOAT Converts numeric to a floating point value
HEX Converts a value to hexadecimal
HOUR Returns hour portion of time, timestamp etc.
INTEGER Converts a number to an integer. Truncate decimal point
LENGTH Returns length of any column which may be null
NULLIF Returns null if two expressions are equal. If not return first
expression
MICROSECOND Returns microsecond portion of timestamp
MINUTE Returns minute portion of a time stamp
MONTH Returns the month portion of a time stamp
SECOND Returns the second portion of timestamp
STRIP Removes leading and trailing blanks from a scalar expression

DB2 HO VER 0.3 14


DB2

SUBSTR Returns a specified portion of a character string


TIME Converts a value to a DB2 time
VARGRAPHIC Converts a character string to a graphic string
YEAR Returns year portion of date, timestamp etc.
VALUE For a null column returns a value instead of null

DB2 HO VER 0.3 15


DB2

DB2 DATA STRUCTURES


4.1) Introduction

In MVS environment, the relational database manager itself is considered as a subsystem. For
each subsystem there are some system objects. DB2 data structures are treated to as DB2 objects. Each
DB2 object is used to support the structure of the data being stored. This section will detail about various
DB2 objects.

4.2) Database

A database is a collection of logically related objects such as tables together with their associated
index and the spaces which contain these tables, and index. It thus consists of a set of tablespaces together
with a set of index spaces. For a stored tables all its associated index must be wholly contained in a single
database.
Objects are grouped together in a database for operational reasons. Operator can make the
database available or unavailable for processing. Database is logical and the data can be contained in single
disk or a set of disk.

4.3 ) Table Spaces

A table space can be thought as a logical (Not in physically adjacent areas) address space use to
hold tables. It is at the tablespace level that storage is actually allocated. The maximum size of tablespace is
64GB and it is divided into pages, which are written to or read from a DASD at the time of an operation.
There is no limit for number of tablespace in a database or number of databases. Table Space can be
divided into three types
 Simple
 Partitioned
 Segmented

4.3.1 ) Simple Table Space

A simple table space can contain one or more stored tables but one is the best option. Since more
than one logically related tables are present, records for different tables can be clustered together to
improve the access times. But in the case of sequential search the system will be slowed down as it has to

DB2 HO VER 0.3 16


DB2

search not only the stored records of the required table but also of the other tables that happen to be mixed
up with first one. So one table per table space is the most satisfactory arrangement for simple table space.

4.3.2) Partitioned Table Space

This is used to store very big tables with large number of rows. In such tables it is operationally
difficult to handle the entire table as one unit. A partitioned table space contains one stored table,
partitioned. Individual partitions are independent so that they can be recovered independent of each other.

4.3.3) Segmented Table Space

This also contains more than one stored tables. But here it will not support cross table clustering
i.e. do not allow the records of different tables to be interleaved on a single page as in simple table space.
Table space is divided in to segments. No segment is allowed to contain records from more than one table.
Sequential access to a particular table is more efficient. This can handle variable length records. So these
are more efficient as compared to simple table space.

4.4) DB2 Stored Tables

This is a stored representation of a base table. It consists of a set of stored records, one for each
data row in the base table. A stored record is not identical to corresponding row of base table. It consist of a
byte string which include
 A stored record prefix containing control information
 Up to N storage fields where ‘N’ is the number of columns of base table
 A length prefix for the field which are of variable length
 A null indicator prefix indicating nulls
 An encoded value of the actual data

There is no gap between the fields. The varying fields contain only the actual value. All internally stored
records are addressed by RID or Record ID. RIDs are unique within the containing table space. From the
figure shown RID contain two parts: The page number and the byte offset from the bottom of the page to
identify the required slot.

DB2 HO VER 0.3 17


DB2

4.5) Index
An index can be defined as a DB2 tool used to locate the row that contains a given value. When a
specific row is required DB2 reads the index finds the pointer to that row and then read the page contains
the row. So Indexing provides uniform and predictable performance for retrieval operations.
Index consist of three levels: a root page, intermediate pages, leaf pages. The leaf level contains an
entry for each distinct value for the indexed field. Intermediate level contains an entry for each leaf page.
Thus root page, intermediate page, leaf page provides a direct and fast access to indexed data. A stored
table can have any number of associated index and hence any number of logical ordering on it.

DB2 HO VER 0.3 18


DB2

4.6) Index Spaces

An index space is used to store an index. The correspondence between index and index space is
always one to one. An index space is created automatically when an index is created. Index spaces can be
recognized and recovered independently.

4.7) Storage Groups

A storage group is a named collection of DASD volumes. Each table space and an index space
normally have a storage group associated with it. Within each storage group data is stored by using VSAM
Linear Data Set (LDS).

4.8) Views

This is a virtual table that consisting of SQL SELECT statements to access data from one or more
tables. A view never stores the data. When user wants to access the view, SQL statement that defines the
view will be executed and the user gets the result. So these can be called as a users table whereas the data
reside in the actual tables on which the view is based. This provides a simplified coding and more security
as the data, which are not required, will be omitted from the view.

DB2 HO VER 0.3 19


DB2

4.9) Alias

A locally defined name for table or a view, in the same local DB2 system or in a remote DB2
system. Alias gives DB2 location independence because an alias can be created for a table at a remote site,
thereby freeing the user from specifying the site that contains the data. Alias can be used as a global one
because it can be used by anyone.

4.10) The hierarchy of DB2 objects.

The following figure demonstrates the hierarchy of various DB2 objects.

DB2 HO VER 0.3 20


DB2

INTEGRITY
5.1) Introduction

The term integrity is used in database contexts to refer to accuracy, validity or correctness of data
in the database. This is very important and is handled by system than by user. Integrity constraints to be
specified during database definition. This will be stored in catalog and will be used by the system during
various operations. DB2 includes two general integrity rules. These are brought into picture using two keys
called primary key and foreign key.

5.2) Primary key

Primary key is a unique identifier for the table. Even that can be composite i.e. more columns can
be combined together to form a unique key. But in a table there can be more than one unique identifier. In
that case table has multiple candidate keys out of which only one will be the primary key and the others
called alternate keys. Primary keys are very important as it provide the basic row level addressing
mechanism. Thus by using the primary key system can pinpoint some specific rows in a required table.

5.2.1) Definition

Primary key can be defined when the base table created through CREATE TABLE or can be
added to an existing table through ALTER TABLE. Every column participating in primary key must be
explicitly declared as NOT NULL. After creating the primary key appropriate unique index has to be
defined. This index called primary index enforces the uniqueness of primary key.
To an existing table primary key can be added using ALTER TABLE command. A suitable
unique index must already exist for ALTER TABLE to succeed, and also the column for primary key
should be declared as NOT NULL.
E.g. CREATE TABLE NTP
(EMPNO CHAR(5) NOT NULL,
EMPNAME CHAR(20) ,
PRIMARY KEY (EMPNO));
CREATE UNIQUE INDEX IND1 ON NTP(EMPNO);
It is also possible to remove the primary key from an existing table.
E.g. ALTER TABLE NTP DROP PRIMARY KEY;

DB2 HO VER 0.3 21


DB2

5.3) Entity Integrity

Entity integrity rule specifies that Primary key should be unique and it should not accept a NULL
value. This is because these values serve to identify the entire row. In the case of composite primary key
each individual value of the primary key should be wholly non null.

5.4) Foreign Keys

A foreign key is a column in one table that matches values to the primary key in another table. The
foreign key can also be null. Each value of the foreign key must match with a corresponding value of
primary key. The table, which contains the foreign key, is called referencing table and the table which
contain the corresponding primary key is called referenced or target table.

5.4.1) Definition

The foreign key can be defined when the base table is created using CREATE TABLE. It can also
be added to or deleted from an existing table using ALTER TABLE. It is not necessary to create an index
on foreign key.
E.g. CREATE TABLE EMP
(EMP# CHAR(5) NOT NULL,
EMPNAME CHAR(20) ,
PRIMARY KEY (EMP#)
FOREIGN KEY FK1 (EMPNO) REFERENCES NTP);
ALTER TABLE EMP DROP FOREIGN KEY FK1;

5.5) Referential Integrity

Referential constraint limits a set of foreign key values to a set of primary key values. So
referential integrity enforces referential constraints. So the database must not contain an unmatched foreign
key value.

5.6) DELETE rules.

When a row contains the primary key is deleted necessary changes to be occurred for the matching
foreign keys. There are three options for this: CASCADE, SET NULL, RESTRICT
 CASCADE when the target row is deleted from target table the row which contain the foreign key of
referencing table also get deleted.

DB2 HO VER 0.3 22


DB2

 SETNULL When the target row is deleted the foreign key will be set to null.
 RESTRICT The delete is restricted.
This rule to be specified when defining the foreign key. Default is RESTRICT.
E.g. CREATE TABLE EMP
(EMP# CHAR(5) NOT NULL,
EMPNAME CHAR(20) ,
PRIMARY KEY (EMP#)
FOREIGN KEY FK1 (EMPNO) REFERENCES NTP ON DELETE CASCADE);

DB2 HO VER 0.3 23


DB2

STRUCTURED QUERY LANGUAGE


6.1) Introduction

SQL is used by DB2 for operating on database. In this programmer has to specify what data he
want to retrieve and not how to do it. In SQL a single request can be formulated in a number of different
but functionally equivalent ways. For example a nested query can always be converted to an equivalent
join. SQL is a nonprocedural language. An SQL manipulation statement can operate on a table and the
result can be obtained on another table. One retrieval statement can retrieve multiple rows or one update
can update can change multiple rows. This feature is called relational closure, which makes relational
database much easier.

6.2) Types of SQL

SQL can be categorized based on functionality. On the basis of this, it is divided into three
 The Data Control Language(DCL) provide the control statements that govern data security
 The Data Definition Language(DDL) for creating and maintaining the data structure
 The Data Manipulation Language(DML) for accessing and modifying the data

Another way to classify SQL is by execution type. There are two types
 The production where the SQL is planned and executed. Here all the requirements are well known
 The ad-hoc where its undefined until an immediate need is identified

Another classification is based on the existence.


 Embedded SQL where the SQL statements are embedded in program
 Stand-alone where only SQL statements are used. No program required

SQL can also be categorized based on Dynamism


 Dynamic SQL is that which is changeable at runtime. This can be either typed from the terminal at
runtime or can be constructed by application programs algorithms
 Static SQL is unchangeable at runtime. This will be embedded in application programs.

DB2 HO VER 0.3 24


DB2

DATA DEFINITION LANGUAGE

7.1) Introduction

Data definition statements can be divided into two broad classes: Logical and Physical. The end
user will be normal using the logical statements. The DDL statements are CREATE, ALTER, DROP. The
following table summarizes these operations on various DB2 objects
DB2 Objects CREATE ALTER DROP
Storage Group Y Y Y
Database Y N Y
Tablespace Y Y Y
Table Y Y Y
Index Y Y Y
View Y N Y
In this section logical statements are covered in detail. The principal logical DDL statements are
CREATE TABLE, ALTER TABLE, DROPTABLE,CREATE VIEW, DROP VIEW, CREATE
INDEX,DROP INDEX.

7.2) CREATE TABLE

This creates the base table. A base table consists of rows and columns to define physical
characteristics of data to be stored. The format is
CREATE TABLE <table name>
(column definition [, column definition]...
[, Primary key definition]
[,alternate key definition]
[,foreign-key definition ])
[,other parameters];
The table name which is user defined gives a unique identity to the table. The column definition can take
the form column data-type [NOT NULL/NOT NULL WITH DEFAULT/UNIQUE]
The square brackets are used to show that they are optional. System will take the default values where
applicable.

E.g. CREATE TABLE S


( S# CHAR(5) NOT NULL,
SNAME CHAR(20) NOTNULL WITH DEFAULT,
STATUS SMALLINT NOT NULL WITH DEFAULT,
CITY CHAR(15) ,

DB2 HO VER 0.3 25


DB2

PRIMARY KEY (S#));


Eg2. CREATE TABLE P
( P# CHAR(6) NOT NULL,
PNAME CHAR(20) NOTNULL WITH DEFAULT,
COLOR CHAR(6) NOTNULL WITH DEFAULT,
WEIGHT SMALLINT NOT NULL WITH DEFAULT,
CITY CHAR(15) ,
PRIMARY KEY (P#));
Eg3. CREATE TABLE SP
( S# CHAR(5) NOT NULL,
P# CHAR(6) NOT NULL,
QTY SMALLINT);

7.2.1 ) CREATE TABLE Using LIKE

A new table can be created with the same shape as some existing table using the option LIKE. But
the new table created will not inherit Primary key, Alternate key, Foreign key definitions.
E.g. CREATE TABLE SCOPY LIKE S;
This is same as CREATE TABLE SCOPY
( S# CHAR(5) NOT NULL,
SNAME CHAR(20) NOTNULL WITH DEFAULT,
STATUS SMALLINT NOT NULL WITH DEFAULT,
CITY CHAR(15));

7.3 ) ALTER TABLE

An existing table can be altered by using ALTER TABLE. For example a new column can be
added to an existing table.
E.g. ALTER TABLE NTP ADD EMPLEVEL SMALLINT;
This statement adds a column to the extreme right in the table NTP. This should not be declared as
NOTNULL. But ALTER cannot change the width or data type of an existing column.
7.4 ) DROP TABLE

An existing table can be deleted using this option. The specified table is deleted from the system.
All indexes, views etc defined on this table will be dropped.
E.g. DROP TABLE NTP;

DB2 HO VER 0.3 26


DB2

7.6 ) INDEXES

Indexes can be created and dropped using DDL statements. Any number of indexes can be created
on a base table. The two DDL statements are CREATE INDEX and DROP INDEX.

7.6.1 ) CREATE INDEX

The format for create is as follows


CREATE [UNIQUE] INDEX <index name>
ON <table name> (column[order],column[order);
The order refers to the order of the column, which has two values ASC,DESC represents ascending and
descending order. Default is ASC. Once the index is created it is maintained by the data manager.
E.g. CREATE UNIQUE INDEX IND1 ON EMP (EMP# DESC);

7.6.2 ) DROP INDEX

This is used to delete an index and the corresponding entry will be deleted from the catalog.
E.g. DROP INDEX IND1;

DB2 HO VER 0.3 27


DB2

DATA MANIPULATION LANGUAGE

8.1 ) Introduction

There are four SQL statements for manipulating the data that has been loaded into the tables. They
are SELECT,INSERT,UPDATE,and DELETE. SELECT retrieves the data,UPDATE changes the existing
values, DELETE removes rows from the table, INSERT adds new rows into the table. This section gives a
detailed description of all the four DML statements.

8.2 ) SELECT

SELECT is used to retrieve the data from the base table. The format is
SELECT [ALL/DISTINCT] <column names>
FROM <table name>
[WHERE <conditional expression>]
[GROUP BY <column names> ]
[HAVING <conditional expression>]
[ORDER BY <column names>];
The result of the above query will be another table derived from the base table.

8.2.1) Simple Retrieval

E.g. SELECT EMP#, EMPNAME, EMPLEVEL FROM EMP;


This query selects all the rows of table EMP. An alternate way of selecting the entire table is using *
E.g. SELECT * FROM EMP;
To retrieve some specific columns that column names can only me mentioned in SELECT
E.g. SELECT EMP# FROM EMP;
To eliminate duplicate rows DISTINCT can be used in SELECT statement
E.g. SELECT DISTINCT EMPNAME FROM EMP;
To retrieve computed values, it can be given on SELECT statement.
E.g. SELECT EMP#, EMPLEVEL + 1 FROM EMP; The resultant table will be containing the
computed value.

DB2 HO VER 0.3 28


DB2

8.2.2) Qualified retrieval


A specific record can also be retrieved using some conditions. The conditional expression following
WHERE can be simple comparison or multiple comparisons.
E.g. SELECT * FROM EMP WHERE EMP# = ‘1001’ ;
E.g2. SELECT * FROM EMP WHERE EMP# = ‘1000’ AND EMPNAME = ‘UMA’ ;

8.2.3 ) Retrieval with Ordering

Resultant table obtained as a result of a query can be in an ordered form. For this ORDER BY has
to be used with SELECT.
E.g. SELECT EMP#,EMPNAME FROM EMP WHERE EMPLEVEL = ‘7’
ORDER BY EMPNAME DESC;
Here the required sequence is arranged. The ORDER BY can take either ASC or DESC. ASC is default.
E.g. SELECT EMP#,EMPNAME
FROM EMP
WHERE EMPLEVEL = ‘7’
ORDER BY 2 , DESC;
Here this will produce the same result as above . 2 refer to second column of the resultant table.

8.2.4 ) Retrieval using BETWEEN and IN

To retrieve the values between some specified ranges BETWEEN is used.


E.g. SELECT EMP#,EMPNAME
FROM EMP
WHERE EMP# BETWEEN ‘7000’ AND ‘8000’ ;
The same result can be produced by another query
E.g. SELECT EMP#,EMPNAME
FROM EMP
WHERE EMP# >= ‘7000’
AND EMP# <= ‘8000’ ;
NOT BETWEEN can also be used to exclude a specific range. IN is used in the similar fashion where the
individual comparisons ORed.
E.g. SELECT EMP#,EMPNAME
FROM EMP
WHERE EMP# IN ( ‘8000’, ‘8001’, ‘8002’);
This will produce the same result as
E.g. SELECT EMP#,EMPNAME

DB2 HO VER 0.3 29


DB2

FROM EMP
WHERE EMP# = ‘8000’
OR EMP# = ‘8001’
OR EMP# = ‘8002’ ;
NOT IN can also be used to exclude the specific values.

8.2.5 )Retrieval using LIKE

LIKE can be used to search for a specific character or a string or a character within a string. But
when using the LIKE
 The ‘-‘ stands for a single character.
 The % character stands for any sequence of N characters
 All other character stands for themselves
E.g. SELECT EMP#,EMPNAME
FROM EMP
WHERE EMPNAME LIKE ‘ J%’ ;
This will retrieve all rows having EMPNAME starting with J.
E.g. SELECT EMP#,EMPNAME
FROM EMP
WHERE EMPNAME LIKE ‘%J%’ ;
This will retrieve all rows having J anywhere in the EMPNAME.
E.g. SELECT EMP#,EMPNAME
FROM EMP
WHERE EMPNAME LIKE ‘---J’ ;
This will retrieve the rows with EMPNAME having 4 characters with J as ending one. Not LIKE can also
be used as in previous cases.

8.2.6) Retrieval involving NULL

To retrieve the rows involving NULL values


E.g. SELECT S#
FROM S
WHERE CITY IS NULL;
IS NULL ore IS NOT NULL can be used. But it is illegal to use CITY = NULL.

DB2 HO VER 0.3 30


DB2

8.3 ) JOIN Queries

This is generally used to retrieve data from more than one table.

8.3.1 ) Simple Equijoin

The comparison operator will be ‘=’ in this case.


E.g. Consider two tables S and P.
SELECT S.*, P.*
FROM S, P
WHERE S.CITY = P.CITY;
Resultant table will include a Cartesian product of all the rows having the city same. The above query can
also be written as
Eg2. SELECT * FROM S, P WHERE S.CITY = P.CITY;

8.3.3 ) Greater than Join

This is the case where > is used instead of =


E.g. SELECT *
FROM S, P
WHERE S.CITY > P.CITY;

8.3.4 )Join query with additional conditions

In the WHERE statement more conditions can be added using AND or OR


E.g. SELECT *
FROM S, P
WHERE S.CITY = P.CITY
AND S.STATUS > 20;
More number of tables can also be used. When using it all the table names have to be included in the
FROM statement and Conditions have to be modified accordingly.

8.3.5 ) Joining a table to itself

This query involves joining a table to itself. So here two references of same table are used. Here
two range variables A,B are used. These variables ranges over that specified table only.
E.g. SELECT A.S#, B.S#

DB2 HO VER 0.3 31


DB2

FROM S A,S B
WHERE A.CITY = B. CITY;

8.4 ) SUBQUERIES

Subqueries are nested SELECT. SELECT FROM WHERE is nested within another such
expression.

8.4.1 ) Simple Subquery

e.g. SELECT S#
FROM S
WHERE CITY IN
(SELECT CITY FROM P WHERE P# = ‘P2’);
This will evaluate the nested subquery first. It will get the value of CITY.
E.g. If for P2 the CITY= PARIS
Then the above query will be same as
SELECT S#
FROM S
WHERE CITY IN (‘PARIS’);
The subquery, which is shown above, can be rewritten with a join also. Multiple levels of nesting can also
be included. In the above example in second WHERE another nesting can be added.

8.4.2) Correlated Subquery

This is a type of subquery in which the inner and outer select statements are executed
simultaneously.
E.g., SELECT SNAME FROM S
WHERE ‘P2’ IN
( SELECT P# FROM SP WHERE S# = S. S#);
Here inner nested query requires the variable S# from table S, whose value changes when the system
examines the table S. For example initial value S1 is selected. From the inner SELECT value of P#
corresponding to S1 are obtained. Then it evaluates the outer query. The corresponding SNAME will be
selected. Thus the processing for S1 will be completed. Then it selects the next value of S# from the table S
and the processing continues. A correlated subquery is one, which whose values depend on some variable
that receives its value from outer query. Thus both the queries are simultaneously executed. So such a
subquery has to be evaluated repeatedly instead of once.

DB2 HO VER 0.3 32


DB2

Even in the correlated subquery inner and outer queries can refer to the same table
E.g. SELECT A. P#
FROM SP A
WHERE A.P# IN
( SELECT B.P# FROM SPB WHERE B.S# = A.S#);

8.4.3 ) Scalar Comparison Operator

When using the subquery scalar comparison operators such as =,> etc can also be used.
E.g. SELECT S# FROM S WHERE CITY =
( SELECT CITY FROM S WHERE S# = ‘S1’);

8.5 ) The Existential Qualifier

In existentially qualified condition ‘EXISTS (SELECT....FROM....) ‘ , the expression evaluates


true only when the subquery produces some result. It can be made clear from an example
E.g. SELECT SNMAE
FROM S
WHERE EXISTS
(SELECT * FROM SP
WHERE S# = S.S# AND P# = ‘P2’);
Consider the first SNAME. Let it be SMITH with S#=S1. For SMITH to appear in resultant table
existence test to evaluate to true. It checks for rows with S#= S1 and P# = P2. If it find some rows then
the subquery evaluates true. So the SNAME correspond to that S# can appear in resultant table.
So the EXISTS in SQL evaluates to true if subquery argument returns a nonempty set.
NOT EXISTS can also be used in a similar fashion.

8.6 ) Quantified Comparisons

A quantified comparison operator consists of a scalar comparison operator like = , >, etc followed
by ANY or ALL.
E.g. SELECT PNAME
FROMPWHEREWEIGHT>ALL
( SELECT WEIGHT FROM P WHERE COLOR = ‘BLUE’);
Here the subquery returns the weight of all parts with color blue. The outer SELECT returns the rows with
values greater than all the values of previous result.
Eg2. SELECT S# FROM S WHERE CITY = ANY

DB2 HO VER 0.3 33


DB2

(SELECT CITY FROM P );

8.7 ) Column Functions

Column (Aggregate ) functions, compute from a group of rows, a single value. This provides
capability to aggregate data so as to perform statistical calculations across many rows with one SQL
statement. The column functions are
AVG Average of the values in the column
SUM Sum of the values in the column
COUNT Number of values in the column
MAX Largest value in the column
MIN Smallest value in the column

Eg1. SELECT COUNT(*) FROM S;


This gives the number of rows in the table S.
Eg2. SELECT COUNT (DISTINCT(S#)) FROM S;
This won’t count repetitions.
Eg3. SELECT MAX(WEIGHT) FROM P;
Eg4. SELECT MIN(WEIGHT) FROM P;
Eg5. SELECT SUM(QTY) FROM SP;

8.8 ) GROUP BY

Using this table can be grouped for taking some aggregate values.
E.g. SELECT P#, SUM(QTY)
FROM SP
GROUP BY P#;
This query will give each value of P# along with the sum of QTY for that specific value of P#.
Eg2. SELECT P#, SUM(QTY), MAX(QTY)
FROM SP
WHERE S# <> ‘S1’
GROUP BY P#;

8.9 ) Use of HAVING

When using GROUP BY, to specify condition HAVING is used. So in short HAVING is to
groups is what WHERE is to rows.
E.g. SELECT P#

DB2 HO VER 0.3 34


DB2

FROM SP
GROUP BY P#
HAVING COUNT(*) > 1;

8.10 ) UNION

The UNION operates on two sets of rows and combines them together into a single set. Two sets
of rows must be union compatible. i.e. the two original sets must be of the same shape.
E.g. SELECT P# FROM P WHERE WEIGHT > 16
UNION
SELECT P# FROM SP WHERE S# = ‘S2’ ;
The duplicate rows will always be eliminated. But if the user wants all the rows to be retrieved he has to
use UNION ALL
E.g. SELECT P# FROM P WHERE WEIGHT > 16
UNION ALL
SELECT P# FROM SP WHERE S# = ‘S2’ ;
Any number of SELECT can be UNIONed together. If OREDER BY clause is used it should come as a
part of final SELECT only. In simple equijoin it select the matching rows only. But if any user want both
matching and unmatching rows from any table (Outer Join) UNION ALL can be used.
E.g. SELECT S.*,SP.P#
FROM S,SP
WHERE S.S# = SP.S#
UNION ALL
SELECT S.* ,’ ‘
FROM S
WHERE NOT EXISTS
(SELECT * FROM SP WHERE SP.S# = S.S#);

8.11 ) INSERT

This is used to insert data in to the table created. The format is


INSERT INTO <tablename> [(col1)[col2,col3,..])]
VALUES (literal[literal....])
The values can also be obtained from executing some subqueries.
E.g. INSERT INTO P
VALUES (‘P1’ , ‘CINTHOL’ , ‘YELLOW’ , 10, ‘MADRAS’);
This is case where the column names can be omitted as such since one entire row is inserted.
E.g. INSERT INTO P (P#, CITY, WEIGHT)

DB2 HO VER 0.3 35


DB2

VALUES (‘P7’, ‘ATHENS’ , 24);


This is the case where the values of whole row are not inserted. So Selectively values can be inserted.
E.g. INSERT INTO P (P#)
SELECT P# FROM SP WHERE S#= ‘S1’;
Here we are not directly entering the values but they are selected from table SP.

8.12 ) UPDATE

The UPDATE statement has the general form


UPDATE <tablename>
SET <column = value>
[WHERE <condition>]
This is used to update for the values in the table
E.g. UPDATE P
SET COLOR = ‘YELLOW’,
WEIGHT = WEIGHT + 5,
CITY=NULL
WHERE P# = ‘P2’ ;
This query will update the values as given where value of P# is P2.

E.g. UPDATE SP
SET QTY = 0
WHERE ‘LONDON’ =
( SELECT CITY FROM S
WHERE S.S# = SP. S#) ;
This uses a subqueruy

8.13) DELETE

The DELETE is used to remove row or rows that satisfy the specific condition.
E.g. DELETE FROM S WHERE S# = ‘S5’ ;
This is a single row delete as the specific condition is given. Multiple rows can also be deleted
using a single query
E.g. DELETE FROM SP WHERE QTY > 300 ;
Subquery can also be used similar to previous cases.

DB2 HO VER 0.3 36


DB2

THE CATALOG

9.1 ) Introduction

DB2 catalog can be treated as a system database that contains information about various objects
such as base tables, views etc. Catalog in a DB2 system consists of various system tables. User can
interrogate catalog using standard facilities of SQL language. In DB2 system the catalog consist of 38
system tables. Some of these catalog tables are described below

9.2) SYSTABLES

This catalog table contains a row for every base table in the entire DB2 system. It include the
informations such as NAME of the table, CREATED BY give the user who created the table, CREATOR
which mentions the owner of the table and many other fields.
NAME CREATED BY CREATOR COLCOUNT OTHERINFOS
S JACOB JACOB 4 ------------
P JACOB JACOB 5 -------

9.3 ) SYSCOLUMNS

This catalog table contains a row for every column of each table of the system.
NAME TBNAME TBCREATOR COLTYPE ------------
S# S JACOB CHAR -------------
SNAME S JACOB CHAR ---------------
----- ----- -------- --------- --------------

9.4 ) SYSINDEXES

This catalog table contains a row for every index in the system.
NAME CREATED BY CREATOR TBNAME TBCREATOR ----------------
nameofindex JACOB JACOB S JACOB ----------
---- ----------- ---------- -- ----------- --------------

9.5 ) QUERYING THE CATALOG

The catalog can be queried using SQL statements

DB2 HO VER 0.3 37


DB2

E.g. SELECT TBNAME, TBCREATOR FROM SYSIBM.SYSCOLUMNS


WHERE NAME = ‘S#’ ;
These can also be used for specific case where in a user wanted to find the total number of tables
created by him. Then
E.g. SELECT COUNT(*) FROM SYSIBM.SYSTABLES
WHERE CREATED BY = ‘ JACOB’ ;
The catalog cannot be updated using INSERT UPDATE and DELETE operations.

9.6 ) ALIASES AND SYNONYMS

Alias is an alternate name for a base table. These will help to access the table very easily. For
example if user A create a table X and user B wants to access that table then the fully qualified name
should be given
E.g. SELECT * FROM A.X;
But if user B can create an alias and use it
E.g. CREATE ALIASE T1 FOR A.X;
SELECT * FROM T1;
Will give the same result as in the first case. Even a third user can also use the same alias by giving a fully
qualified name
E.g. SELECT * FROM B.T1;
These can be removed by using DROP statement.
E.g. DROP ALIASE T1;
A synonym is similar to an alias. But the basic difference is that it is private to the user who creates it. Also
synonym unlike alias cannot refer to remote tables.
E.g. CREATE SYNONYM S1 FOR A.X;
This can only be used by user who creates it. Also the table should not be remote. Removing the
SYNONYM can be done by
E.g. DROP SYNONYM S1;

DB2 HO VER 0.3 38


DB2

VIEWS
10.1 ) Introduction

A view is a virtual table that consists of SQL SELECT statements, which can access the data from
base tables. A view never stores the data. But when the view is accessed the SQL statements are executed
to access the data. So the view can access data from more than one table. These views provide with several
advantages. They allow same data to be seen by different users in different ways. The users perception is
simplified because by using a view he can select only those columns that are required. More security can be
given as all the columns that are not visible in the view. View also provides with logical data
independence.

10.2) VIEW DEFINITION

The general syntax is


CREATE VIEW < name> [ ( column[---] ) ]
AS <subquery> ;
E.g. CREATE VIEW VIEW1 (P#, PNAME , CITY)
AS SELECT P#, PNMAE, CITY FROM P WHERE COLOR = ‘RED’ ;
This will create a view with name A.VIEW1 where A is the CREATOR of the view. When the above
subquery is executed the subquery is not executed but simply stored in the catalog (SYSVIEWS) under the
specified name.
The view can be dropped by using DROP option.
E.g. DROP VIEW VIEW1;
Then for the specified view the definition will be removed from the catalog. But when a base table is
dropped all view defined on the base table will be automatically dropped. There is no ALTER view
statement.

10.3) RETRIEVAL Operations

Retrieval operations on a view will be converted into equivalent operations on a base table. But in
some case like when a user tries to create a view column which is derived from something other than a
simple column of the base table it can fail.
E.g. CRETE VIEW PQ (P#, TOTQTY)
AS SELECT P# , SUM(QTY) FROM SP GROUP BY P# ;

DB2 HO VER 0.3 39


DB2

SELECT AVG(TOTQTY) FROM PQ;


This if by simple merging process will give
SELECT AVG (SUM(QTY)) FROM SP GROUP BY P#;
This will fail as SQL will not allow aggegrate functions to be nested. So instead of this what DB2 does is
materializing the view. For example
E.g. CREATE TABLE TEMPPQ (P#, TOTQTY);
INSERT INTO TEMPPQ (P#, TOTQTY)
SELECT P#,SUM(QTY) FROM SP GROUP BY P# ;
SELECT AVG(TOTQTY) FROM TEMPPQ ;
DROP TABLE TEMPPQ ;
So in this case nesting of aggregate functions does not occur.

10.4) UPDATE Operations

Not all views are updatable. This is because a view can be selected from more than one base table.
Also there are chances to affect the various integrity relations. So in such case views are not updateable.
But if in some views we will be able to preserve the tables integrity relations then they are updateable.

DB2 HO VER 0.3 40


DB2

SECURITY AND AUTHORIZATION


11.1 ) Introduction

The security has to be given for protecting against unauthorized disclosure alteration etc in the
database. Each individual user is assigned an authorization id and all the tables that are created by the user
will be owned by this id. Authorization subsystem which allows users having certain privilege to
selectively grant those privilege to others. There are different types of privileges

 Table privilege which allows the user to perform operations on tables


 Plan privilege which are concerned with authorization to execute a given PLAN
 Data base privileges which is concerned with operations such as CREATE table in a Data base
 User privilege which authorize the use of storage objects namely storage groups, tablespace and buffer
pools
 System privilege for the operations such as creation of new database.

11.3 ) GRANT AND REVOKE

For performing a particular operations user must hold the appropriate authority or privilege. These
two commands are associated with granting and revoking of privileges.
The syntax of the grant statements is
GRANT privileges [ON [type] objects ] to users;
E.g. GRANT SELECT ON TABLE S TO <userid>;
Similarly the revoke statements can be used to revoke privileges.
E.g. REVOKE SELECT ON TABLE S FROM <userid>;

11.4 ) The GRANT OPTION

If a privilege is granted to user A using GRANT OPTIONS, then user A can grant the same
privilege to user B.
E.g. GRANT SELECT ON TABLE S TO A WITH GRANT OPTION;
Then user A can grant the same privilege to user B

E.g. GRANT SELECT ON TABLE S TO B WITH GRANT OPTION.


Now if the grant options to User A is revoked by a revoke command it will have a cascading effect i.e. all
the associated privileges granted by A to various users will also be revoked.

DB2 HO VER 0.3 41


DB2

EMBEDDED SQL

12.1 ) Introduction

SQL statements can also be used in application program. So such SQL statements which are
included in the host language program are called Embedded SQL statements. The host languages that
currently supported by DB2 are PL/I, COBOL,FORTAN,C,SYSTEM/370 Assembler language.

12.2 ) Preliminaries.

 Embedded SQL statements should be prefixed by EXEC SQL. And should be terminated by a
termination symbol(e.g. END EXEC).
 An executable statements can appear wherever an executable host language can appear.
 SQL statements can include references to host variables. Host variables should be prefixed by a colon
which helps to identify them from SQL column names. These host variables used should declared in
BEGIN DECLARE SECTION and terminated by END DECLARE SECTION.
 Host variables can appear in SQL data manipulation language where literals are permitted.(E.g. INTO
clause in SELECT, WHERE and HAVING clause where values to be compared etc.)
 Any table used in the program can be declared by means of an EXEC SQL DECLARE TABLE to
make the program more self-documenting.
 SQLCODE AND SQLSTATE are two special host variables to get the feedback information after the
SQL query executed. A SQLCODE zero means that statement executed successfully. If a positive
value then statements executed with some exceptional conditions and a negative value means that the
statement did not execute successfully. The SQLSTATE values consists of two character ‘class code ‘
followed by three character ‘subclass code’ .This will also helps to know whether the SQL statements
are executed successfully. So to find the status every SQL statement in the program should be followed
by a test on SQLCODE or SQLSTATE.
 SQLCA or SQL Communication Area can be included so that it contains the declarations for both
SQLCODE and SQLSTATE. So either use INCLUDE SQLCA or declare SQLCODE and
SQLSTATE explicitly
 Embedded SQL SELECT statement requires INTO clause specifying the host variable so that values
retrieved from database can be assigned. These host variables should have a data type compatible with
the SQL data type of columns from which the values are retrieved. Host variables and database can
have same name.
E.g. EXEC SQL
SELECT STATUS,CITY

DB2 HO VER 0.3 42


DB2

INTO :STATUS, : CITY


FROM S
WHERE S# = ‘S5’
END-EXEC;

This will select the values of STATUS and CITY in to the host variables and SQLCODE will be
set to 0. If there is no row with S#= S5 then SQLCODE will be set to 100. If there is more than a row with
S# = S5 then the program will show an error with SQLCODE negative. If the values retrieved to be null,
the user has to include an indicator variable. For example if STATUS is NULL then
E.g. EXEC SQL
SELECT STATUS,CITY
INTO :STATUS INDICATOR :STATUSIND, : CITY
FROM S
WHERE S# = ‘S5’
END-EXEC;

If the value to be retrieved to be NULL the indicator value will be set to -1 and host variable
remains unchanged. Indicator variable should be declared as 15-bit signed binary integers.
E.g. EXEC SQL
INSERT INTO P(P#, PNAME, WEIGHT)
VALUES (:PNO, :PNAME, :WEIGHT)
END-EXEC;

Eg1. EXEC SQL


UPDATE S
SET STATUS = STATUS + : NEWSTAT
WHERE CITY = ‘LONDON’
END-EXEC;
12.3 ) Operations Involving CURSORS

In the case of singleton SELECT only one row has to be selected and the retrieved values will be
moved into host variable. But in some cases more number of rows have to be selected. DB2 application
programs uses cursor to navigate through a set of rows returned by an embedded SQL SELECT statement.
Cursor is declared, opened, rows are fetched from cursor one row at a time and cursor is closed.
Four distinct operations or cursors are

DB2 HO VER 0.3 43


DB2

12.3.1 )DECLARE

Declare defines the cursor, gives it a name unique to the program in which it is embedded and
assigns and SQL statement to the cursor name. The DECLARE statement does not execute the SQL
statement but merely defines it.

12.3.2 )OPEN

Open is an executable statement. It reads the SQL search fields, execute the SQL statement and
sometimes builds the resultant table. It does not assign values to host variables.

12.3.3)FECTCH

Returns the data from the resultant table one at a time to the specified host variables. If the
resultant table is not built at cursor open time, it is built one by one. When cursors are used for retrieving
multiple rows FETCH statement should be coded in a loop. When no more rows to be retrieved FETCH
statement should return an SQLCODE of +100.

12.3.4)CLOSE

This statement releases all statements used by cursor.


E.g. WORKING-STORAGE SECTION.
01 MORE ROWS PIC X VALUE ‘Y’.

EXEC SQL
DECLARE CURSOR C1 FOR
SELECT S# ,SNAME,STATUS
FROM S
WHERE CITY = ‘LONDON’
END-EXEC.

PROCEDURE DIVISION.
-
-
EXEC SQL
OPEN C1

DB2 HO VER 0.3 44


DB2

END-EXEC.
IF SQLCODE < 0 PERFORM ERR-PARA.
PERFORM PARA1 UNTIL MORE ROWS = ‘N’.
EXEC SQL
CLOSE C1
END-EXEC.
ERR-PARA.
--
--

PARA1.
EXEC SQL
FETCH C1 INTO :S#, :SNAME, :STATUS
END-EXEC.
IF SQLCODE = +100
MOVE ‘N’ TO MORE ROWS.
IF SQLCODE < 0 PERFORM ERR-PARA.
More number of cursors can be opened at any time. There is no limit to the number of cursors permitted per
application program. The cursor should be declared first before doing any processing on it. Update and
Delete can also be done. These are CURRENT forms of UPDATE and DELETE but it cannot be used
when UNION,GROUP BY,ORDRER BY,DISTINCT etc are used. Also this is not used in the case of
subqueries.
E.g. EXEC SQL
DELETE FROM S
WHERE CURRENT OF C1
END-EXEC.

12.3.5)WITH HOLD clause.


When a COMMIT is issued by program all open cursors will be closed unless WITH HOLD
option should be specified. So the current position of cursor can be saved.
E.g. EXEC SQL
DECLARE CURSOR C2 WITH HOLD FOR
SELECT S#,SNAME
FROM S
WHERE CITY = ‘LONDON’
END-EXEC.

DB2 HO VER 0.3 45


DB2

TRANSACTION PROCESSING
13.1) Introduction

A Transaction is a term used to specify the logical unit of work. This can involve any number of
updates in between. Thus it is a sequence of several operations which converts one consistent state of
database into another, without necessarily preserving the consistency in between. Generally explaining if
one transaction reaches its normal termination with all the steps in between working properly, then the
updation will be made permanent. Instead if some SQL ERROR or some system failure occurs, every
changes made will be erased. So it can be said that either full updation or no updation at all,but partial
updation cannot be made. These are taken care by system component called Transaction Manager.
Whenever an UPDATE is done it is not done on the database. If something goes wrong with
system, updation may be revoked either by program or by system. The data in such condition is called as
tentative until either of these happens
 COMMIT
 ROLLBACK
These two are not really database operations like SELECT and UPDATE. They are instructions to
Transaction Manager. A term Synchronization point will be used (Abbreviated as SYNCHPOINT) which
represents the level between two consecutive transactions.

13.2) COMMIT and ROLLBACK

Any updation made in the system is guarantied once it is committed. This could be by way of an
explicit COMMIT given by the program or it could be given by the system, when the task normally
terminates i.e. A successful end of a transaction is signaled as a synchpoint is established. By the way of
COMMIT statement all open cursors will be closed and all record locks will be released.
The SQL COMMIT statement takes the form
COMMIT [work];

ROLLBACK can also be given explicitly in the program or will be issued by the system when the
task abnormally terminates. Here all updations done after the previous SYNCHPOINT will not be saved to
database. Here again all open cursors are closed and record locks are released.
The syntax is
ROLLBACK[work];

DB2 HO VER 0.3 46


DB2

13.3) Three CONCURRENCY PROBLEMS

DB2 being a shared system allows numerous users to access the same database simultaneously.
Any such kind of system requires some kind of control mechanism to ensure that concurrent transaction do
not interfere with each others operation. There are essentially three ways in which things can go wrong.
They are
 The lost update problem
 The uncommitted dependency problem
 The inconsistent analysis problem

13.3.1)The LOST UPDATE problem


Here Consider the two transactions A and B. From the figure given Transaction A retrieves row R
at time t1. Transaction B retrieves row R at t2. Now Transaction A updates row R at time t3. Again
Transaction B updates row R at t4. So transition A’s update is lost at time t4 because Transaction B
overwrites it. So this describes the lost update problem.

TRANSACTION A TIME `TRANSACTION B


------ T0 -------------
FECTCH R T1 -------------
--------- T2 FETCH R
UPDATE R T3 ------------
----------- T5 UPDATE R

13.3.2)The UNCOMMITED DEPENDENCY problem

This occurs when one transaction is allowed to retrieve a row that has been updated by another
transaction and has not yet been committed to database by other transaction.

TRANSACTION A TIME `TRANSACTION B


------ T0 -------------
T1 UPDATE R
FETCH R T2 ------------
T3 ROLLBACK

DB2 HO VER 0.3 47


DB2

13.3.3)The INCONSISTANT ANALYSIS problem

The figure shows two transactions A and B operating on an account ACC1.Transaction A is


summing an account balance and transaction B is transferring an amount 10 from ACC3 to ACC1. The
result produced by A is incorrect. So if A writes back the result into database it would leave the database in
an inconsistent state. Since A has seen an inconsistent state of database it has performed an inconsistent
analysis. But this cannot be an uncommitted dependency as B commits all updates before A sees ACC3.

13.4) Solution.

For solving the concurrency issues technique called Locking is used. The idea of locking is that
when transaction needs to update an object it puts a lock on that object. The effect of this is to lock the
other transactions out of the object thereby preventing any changes on it. These locks can be either shared
lock or exclusive lock.

DB2 HO VER 0.3 48


DB2

13.5) Locking Facilities.

Though DB2 provides implicit locking mechanism locking can also be done by explicit
declarations.

13.5.1) LOCK TABLE

The syntax is
E.g. LOCK TABLE SP IN SHARE MODE.
Eg1. LOCK TABLE P IN EXCLUSIVE MODE.
Where the table should be a base table and not a view. This command acquires an S or X lock on
the entire table as per the command given. Acquiring such lock may not be instantaneous since the program
will have to wait for a time, when all table level locks will be removed. Once this is done table level locks
will be made and if it is a shared one then the other transactions will be able to get shared locks on any
levels.

13.5.2) The ISOLATION parameter

The ISOLATION parameter on BIND command specifies, isolation level for the application plan
being bound. The two options are
 REPETABLE READ
 CURSOR STABILITY

13.5.2.1)CURSOR STABILITY

If a transaction obtains addressability to a particular record by setting a cursor to point to it and


acquires a lock on that record. This lock is in the shared mode and now without updating it, the cursor
removes the addressability i.e. the lock here will be in S mode and it does not change to X mode. Now this
lock can be released without waiting for the synchpoint in the case of CS being used. So CS provide more
concurrency.
13.5.2.2) REPETABLE READ
Cursor Stability though giving more concurrency is not advisable from the
theoretical point of view. So Repeatable Read is made as the default and that is more preferable. Repeatable
Read holds the record level S lock (Shareable Lock) until the next synchpoint similar to the X lock. The
problem here is that the record may be changed by another transaction without the notice of the change
being made, as explained in the lost update problem. But this can be avoided by the Isolation level

DB2 HO VER 0.3 49


DB2

Repeatable Read. Here if a transaction obtains an addressability to record under CS and if there is a
possibility that the transaction may update the record, i.e. the cursor is defined FOR UPDATE, then DB2
issues a Update Lock (ULOCK) for the transaction instead of the X lock. If a transaction holds a U lock
and another transaction requests for a U lock or X lock the request will be put in the wait state. If the first
transaction updates the record, the U lock will be changed to X lock else it will be released when the
addressability is removed. The advantage here is formation of dead locks may be avoided.

13.5.3)LOCK SIZE
For a given table space, the lock size can be specified as PAGE, TABLE, TABLESPACE or ANY
depending on the factor in the CREATE or ALTER TABLE SPACE operation. When TABLE is specified,
locking will be in the table level and when PAGE is specified, locking will be in the page level, when ANY
is specified DB2 itself decides which unit of locking would be optimum. Mostly DB2 acquires page level
lock initially and when the number of page level lock reaches a installation specified threshold value, then
DB2 escalates the level locking to a higher factor.

13.5.4) The ACQUIRE/RELEASE parameters

These parameters in the bind statement specifies when a table space level lock will have to be
acquired or released. For ACQUIRE possible specifications are USE And ALLOCATE, for RELEASE it
is COMMIT and DEALLOCATE. USE means that the Lock is acquired on the first use and ALLOCATE
means that the locks are allocated when the program begins execution. COMMIT means that the table
space level locks are released at each synch point, and in DEALLOCATE the locks will be held until the
program terminates.

13.6) DEADLOCK

It appears when two or more transactions are simultaneously in the wait state when one transaction
waits for the resource held by another while the other waits for the resource held by the first transaction.
When such a condition occurs, there is no other alternative except to detect it and break it. The breaking
part involves choosing one of the deadlock transaction as the victim and either rolling it back or asking it
role back. This releases the deadlock.

DB2 HO VER 0.3 50


DB2

DYANAMIC SQL

14.1)Introduction

Dynamic SQL consists of a set of embedded SOL facilities, that are provided specifically to allow
the construction of generalized on line application. There may be a necessity some times to construct the
required SQL statements dynamically and then to bind and create those constructive statements
dynamically. DB2I is a generalized on-line application, which can accept any valid SQL statements . It uses
the facility of Dynamic SQL to construct suitable SQL statements corresponding to its input, bind and
execute this statements and to return messages and results back to the terminal.
There are different types of Non SELECT Dynamic SQL statements. They are
 PREPARE/ EXECUTE
 EXECUTE IMMEDIATE

14.2) PREPARE/EXECUTE

This class of Dynamic SQL uses PREPARE and EXECUTE to issue SQL statements. Non SELECT
Dynamic SQL cannot issue a SELECT statement.

Eg1.

WORKING-STORAGE SECTION.
-
-
EXEC SQL INCLUDE SQLCA END-EXEC.

01 STRING-VAR.
02 STRING-VAR-LEN PIC S9(4) COMP.
02 STRING-VAR-TEXT PIC X(100).
PROCEDURE DIVISION.

MOVE 39 TO STRING-VAR-LEN.
MOVE “DELETE FROM TAB1 WHERE DEPTNO = ‘A00’” TO STRING-VAR-TEXT.

EXEC SQL
PREPARE STMT1 FROM :STRING-VAR

DB2 HO VER 0.3 51


DB2

END-EXEC.
EXEC SQL
EXECUTE STMT1
END-EXEC.

14.3) EXECUTE IMMEDIATE

EXECUTE IMMEDIATE which combines the functions of both PREPARE and EXECUTE
statements.
E.g. WORKING-STORAGE SECTION.
-
-
EXEC SQL INCLUDE SQLCA END-EXEC.

01 STRING-VAR.
02 STRING-VAR-LEN PIC S9(4) COMP.
02 STRING-VAR-TEXT PIC X(100).
PROCEDURE DIVISION.

MOVE 39 TO STRING-VAR-LEN.
MOVE “DELETE FROM TAB1 WHERE DEPTNO = ‘A00’” TO STRING-VAR-TEXT.

EXEC SQL EXECUTE IMMEDIATE : STRING-VAR END-EXEC.

DB2 HO VER 0.3 52


DB2

ADMINISTRATION FACILITIES

15.1) Introduction

This falls into two categories. They are facilities for database and facilities for system
administration. The database administration involves the design implementation and maintenance of
individual DB2 database and associated application. Two DB2 features that can assist these tasks are
DB2I and EXPLAIN facility. The system administration covers the installation, monitoring, tuning and
control of overall DB2 system itself.

15.2) DB2 INTERACTIVE INTERFACE

Almost all functions of DB2 are available online through the DB2 interactive interface. This
provides the ability to execute SQL statements interactively and to invoke pre-written application
programs. Apart from this they also have ability to issue operator commands, the ability to invoke database
utilities and the ability to prepare application programs for execution. Though DB21 is the normal mode of
operation, it is always possible to use batch. TSO supports both batch and online application. The online
application work under the control of ISPF. DB2I itself is a TSO online application, which provides the
ability to execute SQL statements interactively by means of a component call SPUFI (SQL Processor Using
File Input).
The following are the sequence of events for invoking DB2I

1. LOGON to TSO in the normal way


2. From ISPF Primary option menu, select DB21 option

Here we get the DB21 main menu with


 SPUFI
 DCLGEN
 Program Preparation
 Pre-compile
 Bind / Rebind / Free
 RUN
 DB2 Commands
 Utilities
 Catalog visibility

DB2 HO VER 0.3 53


DB2

 DB2I Defaults
 Exit

15.2.1) SPUFI

This reports the interactive execution of SQL statements from TSO terminals. The idea here is that
the user can create a text file containing one or more SQL statements then execute the statement through
SPUFI and then use ISPF browse to browse the result.

15.2.2) DCLGEN

This allows the user to invoke the Declaration Generator program. This is the program that creates
embedded SQL, DECLARE TABLE statements and corresponding host language structure declarations
from table description in the catalog. The output from this is stored as a modules of a PDS which could be
copied by the include statement or to put up in the program itself.

15.2.3)Program Preparation

This allows the user to perform any of the following or all of the following functions.
 Precompilation
 Compilation or assembly
 Linkage editor processing
 Bind processing
 Program execution (TSO application only)

15.2.4)Precompile

This is effective only for the precompile step of the program preparation .

15.2.5) Bind / Rebind / Free

BIND creates the application plan from one or more DBRM'S. The following parameters may be specified.
 If the new plan is to replace the existing one
 The AUTH ID that is to own the plan if that ID is different from the ID of the user entering the bind
command.
The isolation level RR & CS specifies the lock acquisition and release times for the plans.

DB2 HO VER 0.3 54


DB2

REBIND rebinds the existing plan. It is not a replace version of the bind command. Here the input for the
rebind command is the previous plan but not the DBRM.

15.2.5) RUN

RUN allows the user to execute a previously prepared application program.

15.2.6) DB2 Commands

This allows the user to enter system operator commands like START DATABASE, STOP
DATABASE etc.

15.2.7)Utilities

This allows the user to invoke various utilities

15.2.8)Catalog Visibility

Catalog Visibility menu allows certain queries to be formulated against DB2 catalog with out
direct use of SQL.

15.2.9) DB2I Defaults

This menu allows the user to set certain defaults for DB2I session

15.2.10) EXIT

This option allows the user to come out of DB2I session.

15.3) EXPLAIN

This allows the user to obtain information regarding the operators choice for the access strategy
specified for the SQL statement.
E.g. EXPLAIN PLAN FOR
SELECT SNO, NAME

DB2 HO VER 0.3 55


DB2

FROM TAB
WHERE CITY = PUNE

15.4) Database utilities

The DB2 database utilities are all online utilities and can be invoked online without stopping the
execution of DB2 system. Some of them are.
 CHECK This utility checks a table space to find if there are any referential integrity violation. Records
if found to contain any unmatched foreign key value, the table space will be in the check pending state.
 COPY This utility creates a full or incremental back-up copy of the table space. An incremental copy is
a copy of the pages that have changed since the previous change
 LOAD This utility loads data from a sequential data set into one or more tables with one or more
partitions of a specified table space.
 MERGE COPY This utility merges a full copy and one or more incremental copies to produce a upto
date full copy.
 MODIFY This is used to perform maintenance operation recovery information in the DB2 catalog.
 RECOVER This uses the most recent full copy, any subsequent incremental copies, and any
subsequent log data to recover one or more table space partitions or pages after a media failure
 REPAIR This can be used to reset conditions like check pending.
 REPORT This produces some reports that are useful in connection with managing database recovery
process
 RUNSTATS This computes statistics on specified stored data and writes them to the system catalog.
 STOSPACE This gathers information regarding the amount of space allocated to a given set of table
space and indexes and stores them in a DB2 catalog.

DB2 HO VER 0.3 56

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