Professional Documents
Culture Documents
DB2 - IBM's Relational DBMS
DB2 - IBM's Relational DBMS
DB2 - IBM's Relational DBMS
Day 1 Topics
Topics to be covered in this session
• Introduction to databases - covers their advantages and the types of
databases
What is Data ?
‘A representation of facts or instruction in a form suitable for
communication’ - IBM Dictionary
What is a Database ?
‘Is a repository for stored data’ - C.J.Date
Introduction to Database (contd...)
• Hierarchical Model
• Network Model
• Relational Model
• Object-Oriented Model
Types of Databases (contd...)
HIERARCHICAL
• Top down structure resembling an upside-down tree
• Parent child relationship
• First logical database model
• Available on most of the Mainframe computers
• Example - IMS
Types of Database (contd...)
NETWORK
• Does not distinguish between parent and child. Any record type
can be associated with any number of arbitrary record types
• Example - IDMS
Types of Database (contd...)
RELATIONAL
• Data stored in the form of tables consists of multiple rows and
columns.
• Examples - DB2, Oracle, Sybase, Ingres etc.
• Relation : A table
• Tuple : Row contains an entry for each attribute
• Attributes : Columns or the characteristics that define the
entity
• Domain:. A range of values (or Pool)
• Entity : Some object about which we wish to store information
• Null : Represents an unknown/empty value
• Atomic Value: Smallest unit of data; the individual data value
Relational Concepts (contd...)
• Candidate key : Some attribute (or a set of attributes) that may
uniquely identify each row(tuple) in the relation(table)
• Alternate key :The above remaining candidate keys that were not
chosen as primary key can be alternate key.
• 1NF : All entities must have a unique identifier, or key, that can be
composed of one or more attributes. All attributes must be atomic and
non repeating.
• E-R models are outputs of analysis phase i.e they are conceptual
data models expressed in the form of an E-R Diagram.
E-R Model Example:
Example:
CUSTOMER Places ORDERS
ORDERS Has PRODUCTS
Table ‘CUSTOMER’
Attributes - CUST_NO, CUST_NAME,
CUST-LOCATION, CUST_SSN, ORDER_NO...
• DB2 provides SQL which performs these functions. The next part
briefly deals with SQL and its functions. A detailed explanation will be
taken up later.
Topics to be covered in this session
• SQL - all data object manipulation, creation and use, involve SQL’s.
• Very flexible
SQL - Features
Catlog
Stored Stored Stored Table
Stored table
table table table
Table Space
Catlog
Table
Stored table Stored table
Stored table
Index Space
Index
Index
Index
Catalog
User Database User Database
Database
• Each table space and each index space normally has an associated
storage group.
• In a given database, all the spaces need not have the same
storage group.
Tablespaces
• Can contain more than one stored table, but in a segmented space.
What is an Index ?
‘An index is an ordered set of pointers to rows of a base table’.
Or
‘An Index is a B-tree structure that orders the values of columns in
a table’
Why an Index ?
‘One can access data directly and more efficiently’
Indexes (contd...)
• When you define an index using the CREATE INDEX statement, DB2
builds this structure and maintains it automatically.
VIEWS
• It is a logical derivation of a table from other table/tables. A View does
not exist in its own right.
Aliases
• Mean ‘another name’ for the table.
• Aliases are used basically for accessing remote tables (in distributed
data processing), which add a location prefix to their names.
• Using aliases creates a shorter name.
Synonym
• Also means another name for the table, but is private to the user who
created it.
DB2 Data types
• Char (n) 1 < n < 254 bytes
• Varchar(n) variable length
• Smallint 2 bytes +- 32 K
• Integer 4 bytes +- 2 GB
• Decimal(x,y) max 31 digits
• Date 0001-01-01
• Time 00:00:00
• Timestamp 0001-01-01-00.00.00.000000
Data Definition Language
CREATE
This statement is used to create various DB2 objects.
Create Table
Syntax : For Creating a Table
CREATE TABLE <tabname>
(Col1 datatype [not null [with default]] ….),
PRIMARY KEY(Columns) /
FOREIGN KEY col1 references tablename
on delete cascade/restrict/set null
[LIKE Table name / View name]
[IN Database.Tablespace Name ]
Data Definition Language
Create Table Parameters
• The conditions that can be used are CASCADE, RESTRICT & SET
NULL (referential constraint for the foreign key definition)
• Inserting (or updating ) rows in the target is allowed only if there are
no rows in the referencing table
Data Definition Language
Create Index
• Create [unique] index indexname
on tablename (col1 [desc], ….)
[using stogroup stgrp1]
[bufferpool BPn]
[close yes/no]
[freepage N]
[pctfree N]
Data Definition Language
ALTER
This statement is used for altering all DB2 objects
DROP
This statement is used for dropping all DB2 objects
• The WHERE clause defines the Predicates for the SQL operation.
• The above WHERE clause can have multiple conditions using AND
& OR .
Other Clauses
Many other clauses can be used in conjunction with the
WHERE clause to code the required predicate, some are :-
• In / Not In
Between Clause
E.g. SELECT CUST_NO, CUST_NAME, CUST_ADDR FROM
CUSTOMER
WHERE CUST_NO BETWEEN 1000 AND 2000;
In Clause
E.g. SELECT CUST_NO, CUST_NAME, CUST_ADDR FROM
CUSTOMER
WHERE CUST_NO IN(1000, 1001,1002);
Select clause (contd...)
Like Clause
E.g. SELECT CUST_NO, CUST_NAME, CUST_ADDR
FROM CUSTOMER
WHERE CUST_ID like/not like ‘425%’
However if there are null values for ORDER_NO, then these are
always evaluated as a ‘Not True’ condition in a Query.
Order by and Group by clauses :
• Order by sorts retrieved data in the specified order; uses the WHERE
clause
• Column Function
• Scalar Function
Column Functions
1. Subqueries and
2. Joins
Subqueries
• The nested loop statements gives the user the flexibility for querying
multiple tables
OUTER JOIN : For one or more tables being joined, both matching and
non-matching rows are returned. Duplicate columns may be
eliminated
The non-matching columns will have nulls in them.
INNER JOIN: Here there is a possibility one or more of the rows from
either or both tables being joined will not be included in the table that
results from the join operation
Other DML Statement’s
INSERT
UPDATE
DELETE
• SPUFI menu contains the input file in which the SQL statements are
coded, option for default settings and editing and the output file.
Reference Book
• DB2 developer’s Guide - Craig S. Mullins
• IBM Manuals
1. SC26-4889 DB2 Application Programming and SQL Guide
2. SC26-4890 DB2 SQL Reference
Day 2 - Topics
Using DB2 In An Application Program
• SQL statement can be embedded in application programming
languages like COBOL.
Comparison of a DB2/VSAM program
DB2 Tables do not require file references,such as
EXEC SQL
SELECT Cust_No, Cust_name, Cust_addr
INTO :H-CUST-NO,
:H-CUST-NAME,
:H-CUST-ADDR
FROM CUSTOMER
WHERE CUST_NO = :H-CUST-NO
END-EXEC.
About Table Declaration
DCLGEN
EXEC SQL
INCLUDE source code name
END-EXEC.
SQL Communication Area
SQLCA
program.
SOURCE Pre-compiler
PROGRAM MODIFIED
SOURCE
DCLGEN CODE
DBRM BIND
PACKAGE COMPILER
BIND
PLAN PACKAGE OBJECT
CODE
PLAN
DB2 LINK-
DB2 DIRECTORY
CATALOG EDIT
LOAD
MODULE
DB2 Program Execution
PRECOMPILE
• The SQL statements coded in the host language must first be translated
by DB2 precompiler for compilation as host language statement.
• Searches all the SQL statements and DB2 related INCLUDE members
and comments out every SQL statement in the program
• All SQL statements are extracted and put in a Database Request Module
(DBRM) .
DB2 Program Execution
PRECOMPILE (Contd….)
• Versioning
DB2 Program Execution
BIND TYPES
DBRM DB2
LIBRARY CATALOG
BIND
Data Base Physical Storage
access PLAN Characteristics
requests
Day 3 - Topics
Topics to be covered in this session
• Cursors
• Null Indicator
• Isolation Levels
• Performance Considerations
Cursors
• Cursor is a mechanism by which DB2 allows an application
program to retrieve a set of (multiple) rows and processes the set
one row at a time.
• Open : readies the cursor for row retrieval; sometimes builds the
result table. However it does not assign values to the host
variables
• Fetch : returns data from the results table one row at a time and
assigns the value to specified host variables
EXEC SQL
DECLARE EMPCUR CURSOR FOR
SELECT Empno, Empname,Dept, Job
FROM EMP
WHERE Dept = 'D11'
FOR UPDATE OF Job
END-EXEC.
Cursors (contd...)
OPEN
E.g. - For the Open statement
EXEC SQL
OPEN EMPCUR
END-EXEC.
Cursors (contd...)
FETCH
E.g. - For the Fetch statement
EXEC SQL
FETCH EMPCUR
INTO :Empno, :Empname, :Dept, :Job
END-EXEC.
Cursors (contd...)
CLOSE
E.g. - For the Close statement
EXEC SQL
CLOSE EMPCUR
END EXEC.
Cursors (contd...)
WHENEVER
EXEC SQL
WHENEVER NOT FOUND
Go To Close-EMPCUR
END EXEC.
EXEC SQL
UPDATE EMP
Set Job = :New-job
WHERE current of EMPCUR
END EXEC.
Some facts about Cursor
• The cursor described in previous slides is non-scrollable cursor. It
always moves sequentially forward in result table.
EXEC SQL
FETCH ABSOLUTE +5 C1
INTO :HVDEPTNO,:DEPTNAME,:MGRNO
END-EXEC.
|
Isolation Level
• The isolation level associated with an application process defines the
degree of isolation of that application process from other concurrently
executing application processes. The isolation level of an application
process, P, therefore specifies:
UR CS RS RR
Can the application s ee uncommitted changes made by other Yes No No No
application proces s es ?
Can the application update uncommitted changes made by other No No No No
application proces s es ?
Can "updated" rows be read by other application proces s es that Yes Yes Yes Yes
are running at the UR is olation level?
Can "acces s ed" rows be read by other application proces s es ? Yes Yes Yes Yes
Application development guidelines
1. A –ve number indicates that the column has been set to null.
2. The value of 2 indicates that the column has been set to null as a
result of data conversion error.
3. A +ve or zero value indicates that the column is not null.
4. The indicator variable contains original length of column in case
of truncation during retrieval of data into host variable not large
enough.
Example for Null Indicator
05 H-CUST-ADD-IND PIC S9(4) COMP.
:
:
EXEC SQL
FETCH CUR1
INTO :H-CUST-NO,
:H-CUST-NAME,
:H-CUST-ADDR1,
:H-CUST-ADDR2:H-CUST-ADD-IND
END-EXEC.
Few SQL Codes …
• -181 The string representation of a date-time value is not a valid date-
time value
• -205 Column-name is not a column of table table-name
• -208 The order by clause is invalid because column name is not part of
the result table
• -407 An update or insert value is null, but the object column column-
name cannot contain null values
• -501 The cursor identified in a fetch or close statement is not open
• -502 The cursor identified in an open statement is already open
Few SQL Codes
• -504 The cursor name cursor-name is not defined
• -551 The auth-id does not have the privilege to perform operation
operation on object object-name
• -811 The result of an embedded select statement is a table of more than
one row, or the result of the sub-query of a basic predicate is more than
one value
• -818 The pre-compiler-generated timestamp x in the load module is
different from the bind timestamp y
• -904 Unsuccessful execution caused by an unavailable resource.
• -911 The current unit of work has been rolled back due to deadlock or
timeout.
Day 4 - Topics
Topics to be covered in this session
• Utilities
• Security and DCL
• Locking
• Catalog Tables
• Optimizer
• Performance Tuning
Db2 - Utilities
• Check
• Copy/MergeCopy
• Recover
• Load
• Reorg
• RunStats
• Explain
Db2 Utilities : Check
• Checks the integrity of DB2 data structures.
• Checks the referential integrity between two tables and also checks
DB2 indexes for consistency.
• Data can be recovered for single page, pages that contain I/O errors,
a single partition or an entire tablespace.
• Indexes are always recovered from the actual table data, not from
image copy and log data, as in the case of tablespace recovery.
• It can place this information in the catalog tables with DB2 optimizer
statistics or DBA monitoring statistics or with all statistics that have
been gathered.
• Two copy steps for each tablespace being reorganized : so that data
is recoverable. The second copy job is required after the REORG if it
was performed with a LOG NO option.
• After a REORG is run with LOG NO option, DB2 turns on the copy
pending status flag for tablespaces specified in the REORG.
• A REBIND job for all plans using tables in any of the tablespaces
being organized.
Db2 Utilities : Explain
• This feature can be used to obtain the details about the access paths
chosen by the DB2 optimizer for SQL statements.
• When EXPLAIN is requested the access paths that the DB2 chooses
are put in coded format into the table PLAN_TABLE, which is created
in the default database.
• The other method is specifying EXPLAIN YES with the Bind command
Db2 Utilities : Explain (contd..)
• The information provided include the type of access of particular
tables used in the SQL or Package or Plan, the order in which the
tables or joined in a JOIN, whether SORT is required and so on.
Types :
– ACQUIRE
• Use
• Allocate
– RELEASE
• Commit
• Deallocate
Db2 Locking
• Db2 support locking at three levels:
– Table Space
– Table
– Page
• However the DB2 catalog is semi active only. This is because updates
to number of rows, the physical order of the rows for a set of keys and
the like are updated only after running a RUNSTATS utility.
• DB2 catalog is integrated - DB2 catalog and DB2 DBMS are inherently
bound together.
Db2 : Catalog Tables
It is nonsubvertible - DB2 catalog cannot be updated behind DB2’s
back. i.e. if a table of 10 columns is created, it is not possible to go
and change the number of columns directly on the catalog to 15. It has
to be done using the standard SQL statements for dropping and
recreating the table .
Db2 : Catalog Tables