0% found this document useful (0 votes)
295 views261 pages

DB2 Application Programming'

Uploaded by

api-19903451
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
295 views261 pages

DB2 Application Programming'

Uploaded by

api-19903451
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 261

DB2 Application Programming`

DB2
Course Objectives

After completing this course you should be able to


 
List and describe the major functions, components and
data management techniques for DB2
 
Describe DB2’s SQL and its efficient use with 3GL
languages like COBOL
 
Use DB2 associated facilities like LOAD, RUNSTATS
DB2 : Some History

 
Research : System R

1983 : DB2 Version 1


 
Research : System R*
Starburst
 
1995 : DB2 version 4
DB2 and MVS

IMS CICS TSO


Terminal Terminal Terminal

IMS/DC CICS TSO TSO

IMS IMS CICS TSO TSO


CAF
Batch Online Online Online Batch
Application
Application Application Application Application Application

IMS/DB DB2

MVS
IMS Databases DB2 Databases
Course Plan

Introduction to Relational Model


DB2 Data Management
DB2 Data Management
DB2 Functions and Components
SQL – Data Definition Language
SQL – Data Manipulation Language
DB2 – Application Programming
DB2 – Program Preparation
DB2 – Efficient SQL Coding
DB2 – Security.
Relational Model

An overview
Relational Model
Relational Data Structure
Table
 
Relational Data Integrity
Entity Integrity
Referential Integrity
 
Relational Data Manipulation
Relational Algebra
Relational Data Structure.

Attribute

Emp Name Age Sex Dept# Join_Date


 
2000 Vijay 33 M 101 01/01/85
3000 Gupta 24 M 102 01/01/85
1000 Sridevi 29 F 101 01/02/96
2500 Patel 29 M 103 01/01/88
Properties of Tables
Each row-column entry in table consists of an atomic data
element
 
All the data elements in a given column are of the dame
data type
 
Each column in a table has a unique name
 
Sequence of rows in the table is not meaningful
 
All the rows in the tanle are unique.
Missing Values : NULL

Column Value
-         Not Applicable
-         Not Available
 
Emp Name Project Join_Date
2000 Vijay GE 01/01/85
3000 Gupta ? 01/01/96
4000 Sridevi HP 01/02/95
Relational Data Integrity

Primary Key
-         Uniqueness
-         Minimality
 
Alternate Key
 
Foreign Key
Foreign Key

Department 
Dept Name Location
101 Marketing Chennai
102 Personnel Mumbai
103 Admin Chennai
104 Training Chennai

Emp NameDept Join_Date Dept


2000 Vijay 101 01/01/85 Primary Key of
3000 Gupta 102 01/01/96 Department table
4000 Sridevi 103 01/02/95 Foreign Key of
Employee table
Integrity Constraints

Entity integrity
 
No column in the primary key can have a NULL value
 
Referential Integrity
 
Every foreign key value must either match a primary key
value of its associated parent table or it must be wholly
NULL .
Relational Algebra
Restrict Project Join Divide
Union Intersection Difference Product
 
Properties
 
They operate on all entire table; they donot operate on
individual rows of the table.
 
When the relational operator is applied to on or more
tables, the operation results in another table
RESTRICT

Emp Name Project Join_Date


2000 Vijay GE 01/01/85
3000 Gupta ? 01/01/96
4000 Sridevi HP 01/02/95

Emp Name Project Join_Date


3000 Gupta ? 01/01/96
Project

Emp# Name Project Join_Date


2000 Vijay GE 01/01/85
3000 Gupta ? 01/01/96
4000 Sridevi HP 01/02/95

Emp # Join_Date

2000 01/01/85 Project


Emp #
Join_date
3000 01/01/96

4000 01/02/95
JOIN

a1 b1

a2 b1
a1 b1 c1
a3 b2
JOIN a2 b2 c2

b1 c1 a3 b3 c3

b2 c2

b3 c3
INNER JOIN

Emp# Name Project Join_Date


2000 Vijay GE 01/01/85
3000 Gupta ? 01/01/96
4000 Sridevi HP 01/02/95

Dept# Name Location


101 Marketing Chennai
102 Personnel Mumbai
104 Training Chennai

Join on Dept#

Emp# Name Project Join_Date Name Location


2000 Vijay GE 01/01/85 Marketing Chennai
3000 Gupta ? 01/01/96 Personnel Mumbai
Left Outer JOIN

Emp# Name Dept Join_Date


2000 Vijay 101 01/01/85
3000 Gupta 102 01/01/96
4000 Sridevi 103 01/02/95

Dept# Name Location


101 Marketing Chennai
102 Personnel Mumbai
104 Training Chennai

Join on Dept #

Emp# Name Dept# Join_Date Name Location


2000 Vijay 101 01/01/85 Marketing Chennai
3000 Gupta 102 01/01/96 Personnel Mumbai
4000 Sridevi 103 01/02/95 ? ?
Right Outer JOIN

Emp# Name Dept Join_Date


2000 Vijay 101 01/01/85
3000 Gupta 102 01/01/96
4000 Sridevi 103 01/02/95

Dept# Name Location


101 Marketing Chennai
102 Personnel Mumbai
104 Training Chennai

Join on Dept #
Emp# Name Dept# Join_Date Name Location
2000 Vijay 101 01/01/85 Marketing Chennai
3000 Gupta 102 01/01/96 Personnel Mumbai
? ? 104 ? Training Madras
Full Outer JOIN
Emp# Name Dept Join_Date
2000 Vijay 101 01/01/85
3000 Gupta 102 01/01/96
4000 Sridevi 103 01/02/95

Dept# Name Location


101 Marketing Chennai
102 Personnel Mumbai
104 Training Chennai

Join on Dept #

Emp# Name Dept# Join_Date Name Location


2000Vijay 101 01/01/85 Marketing Chennai
3000Gupta 102 01/01/96 Personnel Mumbai
4000 Sridevi 103 01/02/95 ? ?
? ? 104 ? Training Madras
DIVIDE

x
a x
y
a y

a z Divide
b x
a
c y
UNION

Emp # Name

2000 Patel Emp # Name

3000 Gupta 2000 Patel

3000 Gupta
UNION 2500 Singh

Emp # Name 3000 Gupta

5000 Hari
2500 Singh
6000 Guru

3000 Gupta

5000 Hari

6000 Guru
INTERSECTION

Project 1
Emp # Name

2000 Patel

3000 Gupta

INTERSECTION
Project 2
Emp # Name

2500 Singh
Emp # Name
3000 Gupta
3000 Gupta
5000 Hari

6000 Guru
DIFFERENCE

Project1
Emp # Name

2000 Patel

3000 Gupta

Project 2 Difference
Emp # Name

2500 Singh
Emp # Name
3000 Gupta
2000 Patel
5000 Hari

6000 Guru
CARTESIAN PRODUCT

a x
a
a y
b
b x
c b y
PRODUCT
c x
x
c y

y
Relational Model : Some Advantages

* Easy to Understand
 
* Elimination of need to preplan “ HOW “ to get to
data
 
* Flexibility
Data Management in DB2

An Introduction
DB2 Data Objects

 
        Storage Group
        Databases
        Tablespaces
        Indexes
        Bufferpools
        EDM pool
        BSDS
        Logs
DB2 Tablespaces

Logical Representation Physical


Representation
Pages

A page is either 4K or 32K

A page is the unit of I/O

A page can contain a max.


of 127 data records.

A data record does not


Span pages
HEADER

FOOTER
Simple Tablespaces

Table 1 - Row X Table 2 - Row C


Table 1 - Row Y Table 3 - Row N
Table 2 - Row A Table 2 - Row D
Table 2 - Row B Table 1 - Row W
Table 1 - Row Z Table 2 - Row E
Table
Page 1 3 - Row M Table
Page 2 3 - Row O
Segmented Tablespaces

Table 1 Table 2 Table 3


Partitioned Tablespaces

Part 1 Part 2 Part 3 Part 4


Indexes

101 1 101

104
102 3
102

103 4 103

104 2

Position
KEY
Indexes : Terminology

Indexing Key Composite Key


Unique Index Non-Unique Index
Primary Index Secondary Index
Partitioning Inddex Clustring Index
B+ Trees
Root Node
25
Intermediate Nodes

8 17 33 40

138 9 11 17 19 21 25 28 31 33 35 38 40 46 51 55

Leaf NodesPointing
to Data Pages
Clustering Index

25

8 17 33 40

138 9 11 17 19 21 25 28 31 33 35 38 40 46 51 55

Data
Pages
Non-clustered Index Scan
Stogroup
Database
Bufferpools
DB2 System Objects

• Bufferpool
• EDM Pool ( Environment Descriptor
Manager )
• BSDS ( Bootstrap Dataset )
• Logs ( Active and Archive logs )
Data Types : String
Data Types : Datetime

Datetime

Time Timestamp Date


Data Types : Numeric

Numeric

Binary Integer Decimal Floating Point

Small Large Small Large


DB2 Functions and Components
An Introduction
DB2 Catalog

Data about data DB2 is managing –


“ Metadata “

Stored in DB2 Tables

Can be accessed in the same way as user


data
Transactions
Begin Transaction
SQL Command
End Transaction
SQL Command All Changes “ DONE”
Begin Transaction
COMMIT

End Transaciton
SQL Command
All Changes“UNDONE”
SQL Command

COMMIT

ROLLBACK
Transactions : An example

Account 1 Account 2
Balance = 2000 Balance = 5000

Transaction

Withdraw 1000 from Account 1


Deposit 1000 from Account 2

Account 1 Account 2
Balance = 1000 Balance = 6000
Transaction : ACID Properties

ATOMICITY

CONSISTENCY

ISOLATION

DURABILITY
Lost Update Problem

User 1
Quantity = 2000 User 2

Send 1000 units Quantity = 2000 Receive 2000 units

Quantity = 2000
Uncommited Read

User 1
Quantity = 2000 User 2

Send 1000 units


Quantity = 1000 Receive 2000 units

ROLLBACK Quantity = 2000

Quantity = 2000
Incorrect Summary Problem
Locking

Lock on data indicates data is being used

Attributes of locks
Object : How much data is marked “in-use”
Duration : How long is the lock is needed
Mode : How severe is the lock
Lock : Object

PAGE or ROW

Great concurrency
More locking overhead

TABLE or TABLESPACE

Less locking overhead


More data is restricted
Lock : Duration

Different options for Application Programs

– ACQUIRE/RELEASE

– ISOLATION LEVEL
Lock : Mode

Shared - Data is being Read


Other users can read the
same data
Exclusive - Data is being changed
No other users allowed
DEADLOCK
Failures

* Hardware Failure

* Program Failure

* Natural Calamity
Backing up data

* IMAGE COPY
* FULL
* INCREMENTAL

* MERGECOPY
* FUZZYCOPY
System Log

[Begin transaction T1]


[T1, table 1, Page 1, Before Image]
[T1, table 1, Page 1, After Image]
[T1, table 2, Page 3, Before Image]
[T1, table 2, Page 3, After Image]
[Begin Transaction T2]
[T2, table 3, Page 9, Before Image]
[T2, table 3, Page 9, After Image]
[End Transaction T2 ]
[End Transaction T1 ]
Recovery

* RECOVER Utility
Tablespace is the unit of recovery

* Point of time recovery

* Disaster Recovery
Integrity Enforcement

• Table Check Constraint


Designates the value that columns of a table can
contain
• Referential Constraint
The limiting of a set of foreign key values to a set
of primary key values.
Security

• Outside Db2
- RACF

• Within DB2
- Privileges
- Administrative Authorities
Application Programming Interface

SQL – Structured Query Language

Embedded SQL DB2 Interactive (DB2l)

SQL

Data Definition Language Data Manipulation Language Data Control Language


DDL DML DCL
Utilities

• LOAD

• UNLOAD

• REORGF

• RUNSTATS
SQL - DDL

DATA

DEFINITION

LANGUAGE
SQL – Structured Query Language

SQL

DDL DML DCL


DDL – DB2 Objects

• Storage Group
• Database
• Tablespace
• Table
• Index
• View
• Synonym
DDL - Opertions

• CREATE - Defines a new object

• ALTER - Modifies an object

• DROP - Deletes a defined object

• Entered interactively or embedded in application


programs.
DDL – OBJECTS vs OPERATIONS

CREATE ALTER DROP

Storage Group X X X

Database X X

Tablespace X X X

Table X X X

Index X X X

Synonym X X
View X X
DDL – System Naming Rules
DDL – CREATE Storage Group

Syntax:
CREATESTOGROUP stogroup-name
VOLUMES (vo11, vo12,…)
VCAT catalog – name
(PASSWORD password)

CREATE STOGROUP TRG1TO1


VOLUMES (DBPKO1, DBPK02)
VCAT DB22OTRG

 
DB2 Application Programming

Using Embedded SQL


Host Languages

•COBOL
•PL/1
•C
•Assembler
•FORTRAN
Embedded SQL

* Delimit all SQL statements


•Declare a Communication Area
•Describe Host Variables
•Code SQL statements to access DB2 data
•Handle Exceptional Conditions
Static SQL

Statement:
Coded in program,always does the same function on the same tables
and columns
Bind: on all SQL statements
Before program execution
Builds a stored Plan/Package
SQL Delimiters in COBOL
EXEC SQL
SQL statement
END –EXEC
•The EXEC and SQL keywords must appearon one line, but the remainder of the statement can
appear on subsequent lines
*The EXEC SQL must notbe coded before column 12
•COBOL comments are allowed any where within the delimiters
INCLUDE

EXEC
INCLUDE SQLCA/ SQLCA member-name
END-EXEC
Member-name
Member of the partitioned data set
The member can contain any COBOL variable declarations, source statements and any SQL
statements other than an INCLUDE statement.
DDL – ALTER Storage Group

Syntax:
ALTER STOGROUP stogroup-name
ADD VOLUMES ( vo14, vo15, …)
REMOVE VOLUMES (vo11, vo12, . . . )
ALTER STOGROUP TRG1TO1
ADD VOLUMES (DBPK03)
REMOVE VOLUMES (DBPK01)
DDL – CREATE Database
Syntax:
CREATE DATABASE database – name
(STOGROUP stogroup – name)
(BUFFERPOOL bufferpool – name)

CREATE DATABASE TRGTO1


STOGROUP TRGITO1
BUFFERPOOL BPO
DDL – CREATE TABLESPACE
Syntax :
CREATE TABLESPACE tablespace – name
IN database-name
USING STOGROUP stogroup – name
PRIQTY qty
SECQTY qty
ERASE YES/NO
LOCKSIZE ANY/PAGE/TABLESPACE/TABLE
BUFFERPOOL BPO/BP1/BP2/BP32K
CLOSE YES/NO DSETPASS password
FREEPAGE <amount> PCTFREE <amount>
DDL – CREATE TABLESPACE Parameters

PRIQTY & SECQTY

* PRIQTY amount of physical storage allocated when


tablespace is created
* SECQTY space taken amount of data in tablespace grows
* specified in KB
DDL – CREATE TABLESPACE Parameters

ERASE:

* Indicates whether the DB2 defined datasets are to be erased when tablespace
is dropped

LOCKSIZE

* Indicates type of locking (Page/Tablespace/Table/DB2 decided


DDL – CREATE TABLESPACE Parameters

BUFFERPOOL:

* Buffer pool to be associated withtablespace


* Defaultvalue is default buffer pool of databse

CLOSE:

* Indicates whether data sets associated with tablespace;should be closed when there are no
current users of tablspace
* Default is YES
DDL – CREATE TABLESPACE Parameters

FREEPAGE:
* Specified number of pages after which
a completely empty page is available
* Default is FREEPAGE 0
PCTFREE:
* Specifies percentage of each page
available for future inserts
* Default is PCTFREE 5
DDL – CREATE TABLESPACE

Example:
CREATE TABLESPACE
IN DSN8DP2AP
USING STOGROUP DSNS62600
PRIQTY 12
SECQTY 12
ERASE NO
LOCKSIZE ANY
CLOSE YES
BUFFERPOOL BPO
DDL – ALTER TABLESPACE

ALTER TABLESPACE tablespace-name


BUFFERPOOL BPO/BP1/BP2
LOCKSIZE ANY/PAGE/TABLESPACE/TABLE
CLOSE YES/NO
DSETPASS password
FREEPAGE amount
PRIQTY qty
SECQTY qty
ERASE yes/No
DDL- CREATE TABLE

Syntax : (Format 1)
CREATE TABLE tablename
(column-definition (, column-definition) . . .
(, primary-key-definition)
(, foreign-key-definition
(, foreign-key-definition) . . .
(other-parameters) )
( IN databasename.tablespacename/
IN DATABASE databasename)
DDL- CREATE TABLE

Syntax : (Format 2)

CREATE TABLE tablename


LIKE existing-tablename
DDL-CREATE TABLE

COLUMN- definition
colname coltype (NOT NULL/ NULL / NOT NULL WITH DEFAULT)
Primary-key definition:
PRIMARY KEY(colname1,colname2,…)
DDL- CREATE TABLE
foreign-key definition:
FOREIGN KEY (constraint-name)
(colname1(, colname2) . . .)
REFERENCES base-table
(ON DELETE RESTRICT/CASCADE/SET
NULL)
DDL-CREATE TABLE

Other parameters:

EDITPROC: edit routine for table

VALIDPROC:validation routine for table


DDL – CREATE TABLE

Example

CREATE TABLE SUPPLIER


(S# CHAR(5) NOT NULL,
SNAME CHAR(20) NOT NULL,
STATUS SMALLINT NOT NULL WITH DEFAULT
CITY CHAR(15) NOT NULL WITH DEFAULT
PRIMARY KEY (S#)
IN TRG1T01.DSN8D2AP
DDL – ALTER TABLE

Syntax:
ALTER TABLE tablename
ADD column-definition
VALIDPROC program-name NULL
primary-key-definition
referential-constrains
CRC? PRIMARY KEY
CRC? FOREIGN KEY constraint - name
DDL – CREATE INDEX
Syntax:
CREATE (UNIQUE) INDEX indexname
ON tablename (colname (ASC/DESC),…)
( USING STOGROUP stogroupname)
PRIQTY qty
SECQTY qty
ERASE YES/NO)
(CLUSTER) (SUBPAGES amount)
(BUFFERPOOL BPO/BP1/BP2)
(CLOSE YES/NO) (DSETPASS password)
(PCTFREE amount) ( FREEPAGE amount)
DDL- CREATE INDEX

Example:
CREATE UNIQUE INDEX XS
ON SUPPLIER (S#)
USING STOGROUP TRG1TO1
PRIQTY 16
SECQTY 4
ERASE NO
DDL – ALTER INDEX
Syntax :
ALTER INDEX index-name
BUFFERPOOL BPO/BP1/BP2
CLOSE YES/NO
DSETPASS password
FREEPAGE qty PCTFREE qty
USING STOGROUP stogroupname
PRIQTY amountSECQTY amount
ERASE YES/NO
DDL – CREATE VIEW

Syntax:
CREATE VIEW view-name
(column-name, . . .)
As subselect
WITH CHECK OPTION
DDL – CREATE SYNONYM

Syntax :
create synonym SYNONYM
FOR auth-id.table-name
DDL – DROP Statement

Syntax:
DROP object-type objectname

Example
DROP DATABASE TRG1TO1
DROP TABLE SUPPLIER
DROP INDEX XS
DDL- DROP Dependencies

DROP DEPENDENCIES
SQL- DML

DATA
MANIPULATION
LANGUAGE

DB2-DML-1
DML Overview

DML verbs are:


* SELECT - Retrieves data
* UPDATE - Changes value(s)
* DELETE - Remove row(s)
* INSERT - Adds new row(s)
will be explained using an example
DML – SELECT Select Overview

Select statement is used to assess data from one or more tables:


(a). Simple Queries (f) Aggregate
(b). Qualified retrieval functions
©. Retrieval with ordering. (g)Grouping
(d) . Join enquiries (h) Union
(e) Subqueries
DML – SECECT Statement

ko m m
ko ko ko
m k
ko m
o
DML – SELECT Statement

Syntax:
SELECT (all) DISTINCT) scalar-expression
FROM table(s)
(WHERE search-condition)
(GROUP BY column(s) )
(HAVING search-condition)
(ORDER BY column(s))
DML – SELECT Statement

Scalar Expressions
(LENGTH (SNAME) –1*2
SALARY+COMMISSION+BONUS

Search Condition
(SUBSTR (SNAME,1,3) = ‘VIJ’
AND
CITY = ‘MADRAS’
DML- SELECT Statement

(a) Simple Queries


• SELECT P#
FROM SHIPMENTS
• SELECT SHIPMENTS. P#
FROM SHIPMENTS
* SELECT DISTINCT P# FROM SHIPMENTS
DML – SELECT Statement

(b) Simple Queried (Contd…)

•SELECT *
FROM SUPPLIER
•SELECT P#, ‘Weight in grams = ‘, WEIGHT * 454
FROM PARTS
DML – SELECT Statement

(b) Qualified Retrieval – using WHERE Clause

SELECT S = FROM SUPPLIERS


WHERE CITY = ‘MADRAS’
AND STATUS > 20;
DML – SELECT Statement
(b) Qualified Retrieval – Using BETWEEN predicate

• * SELECT P#, PNAME, COLOR, WEIGHT, CITY


FROM PARTS
WHERE WEIGHT BETWEEN 16 AND 19

* SELECT P#,PNAME, COLOR, WEIGHT, CITY

FROM PARTS
WHERE WEIGHT NOT BETWEEN 16 AND 19
DML – SELECT Statement

(b) Qualified Retrieval – Using IN predicate

* SELECT P#, PNAME, COLOR, WEIGHT,CITY


FROM PARTS
WHERE WEIGHT IN (12,16,17)
DML – SELECT Statement

(b) Qualified Retrieval – Using LIKE predicate

•Used tosearch for strings that have a certain pattern


•% stands for any sequence of n characters
•- stands for any single character
•SELECT P#, PNAME, COLOR, WEIGHT, CITY
FROM PARTS
WHERE PNAME LIKE ‘C8’
DML – SELECT Statement

© Retrieval with Ordering


•SELECT S#,STATUS FROM SUPPLIER WHERE
CITY=‘Madras’ ORDER BY STATUS DESC
ASC/DESC – Puts row in ascending of descending
order.Default is ASC
DML – SELECT statement
(d) JOIN QUERIES – Simple quijoin
•SELECT SUPPLIER.*, PARTS.* FROM SUPPLIER, PARTS WHERE
SUPPLIER.CITY = PARTS.CITY

•* In the absence of WHERE clause, the result is the cartesian product


of the tables in the FROM
DML – SELECT Statement

(d) JOIN queries – Greater – Than Join

* SELECT SUPPLIER.* PARTS.* FROM SUPPLIER, PARTS WHERE


SUPPLIER.CITY, PARTS.CITY
* Join criteria can have other operators like >=, <>, <.<=
DML – SELECT Statement

(d) JOIN queries – Selef – Join

•Jon of a table with itself


•SELECT FIRST.S#, SECOND.S# FROM SUPPLIER FIRST,SUPPLIER
SECOND WHERE FIRST.CITY = SECOND.CITY
•FIRST AND SECOND are Range Variables of Correlation Names
DML – SELECT Statement
(d) JOIN queries – Multi-table-joins

•SELECT DISTINCT SUPPLIER.CITY, PARTS.CITY FROM SUPPLIER,


SHIPMENTS, PARTS WHERE SUPPLIER.S# = SHIPMENTS.S# AND
SHIPMENTS.P# = PARTS.P#
• A maximum of 15 tables can be joined in an SQL statement
DML – SELECT statement

(e) Subqueries of Nested Selects

•Simple Subquery
•SELECT SNAME FROM SUPPLIER WHERE S# IN (SELECT S# FROM
SHIPMENT WHERE P# = ‘P2’)
DML – SELECT Statement

(e) Correlated subquery


•A nested SELECT statement referring back to columns in out SELECT
statements
• SELECT SNAME FROM SUPPLIER WHERE ‘P2’ IN (SELECT P# FROM
SUPPLIER WHERE S# = SUPLIER.S#)
DML- SELECT Statement

(e) Joins VERSUS Subquries


* A subquery can be converted to an equivalet join
* Joins are more efficient than subqueries in DB2
DML – SELECT Statement

(f) Existential Quantifier

* Used to test for existence of certain rows


* SELECT SNAME FROM SUPPLIER WHERE EXISTS (SELECT *
FROM SHIPMENT WHERE S# = SUPPLIER.S# AND P# = ‘P2’)
DML – SELECT Statement
(g) Aggregate or Column Functions

•Functions operate on collection of values in a column


•Count – number of values in the column
•SUM - sum of values in the column
•AVG - average of the values in the column
•MAX - largest value in the column
•MIN - smallest value in the column
DML – SELECT Statement

(g) Aggregate Function – Examples


•SELECT COUNT(*) FROM SUPPLIER
• SELECT SUM(QTY) FROM SHIPMENT WHERE P# = ‘P2’
DML – SELECT Statement
(h) Grouping

Partition or Groups the rows based on given criteria

* SELECT P#, SUM(QTY) FROM SHIPMENT GROUP BY P#


DML – SELECT Statement

(h) Grouping (Contd…)

* SELECT p#, SUM(QTY), MAX(QTY) FROM SHIPMENT WHERE S#


<> ‘S1’ GROUP BY P#
DML – SELECT Statement

(h) Grouping – HAVING Clause

•HAVING is to groups what WHERE is to rows


• SELECT P# FROM SHIPMENT GROUP BY P# HAVING COUNT(*) > 1
DML – SELECT Statement

UNION
Union operation on union-compatible sets of rows

•SELECT P# FROM PARTS WHERE WEIGHT > 16


UNION
SELECT.P# FROM SHIPMENT WHERE S# = ‘S2’
Dml – DATE / TIME Arithmetic
Duration:

Date duration: yyyymmdd


Time duration: hhmmss
Timestamp duration: yyyymmddhhmmssnnnnn
Microsecond duration: nnnnnn
Dml – DATE / TIME Arithmetic

Labeled Duration:
•N units

n : any numeric expression


Units : YEAR[S],
MONTHS[S],DAY[S],HOUR[S],MINUTE[S],SECONDS[S],MICROSECOND[S]
e.g., 3 YEARS, 90 DAYS, 1 MINUTE
Dml – DATE / TIME Arithmetic

Extraction of Date / Time Components:


•YEAR , MONTH, DAY
•HOUR,MINUTE,SECOND
•MICROSECOND
Dml – DATE / TIME Arithmetic

Conversions To ? From other Data Types:

•DATE, TIME, TIMESTAMP


•CHAR
•DAYS
Dml – DATE / TIME Arithmetic

Special Registers:
•CURRENT TIMEZONE
•CURRENT DATE
•CURRENT TIME
•CURRENT TIMESTAMP
DML – DATE / TIME Arithmetic

Examples:
•DATE(‘8/17/1996’) – DATE(’10/28/1996’)
•START_DATE + 1 YEAR + 6 MONTS
•CURRENT TIMESTAMP + 1 SECOND
•START_TIME – END_TIME < 080000
DML – INSERT Statement

Syntax:
INSERT INTO table[ (column [, column] …)]
Values (literal [,literal]….)

Or
INSERT INTO table [ (column[, column] …)]
subquery
DML – INSERT Statement
Examples

INSERT INTO PARTS (P#, CITY, WEIGHT)


VALUES (‘P7’, ‘CALCUTTA’, 24)

INSERT INTO PARTS VALUES (‘P8’, ‘SPROCKET’ , ‘PINK’, 14,


‘SHIMLA’)
DML – INSERT Statement

Insert with a subquery

INSERT INTO TEMP (P#, TOTQTY) SELECT P#, SUM(QTY) FROM


SHIPMENT GROUP BY P#
DML – INSERT Statement
Insert with Referential Integrity

•Referential constraint from SHIPMENTS.S# to SUPPLIERS.S#

INSERT INTO SHIPMENTS.S#, P#, QTY) VALUES (‘S20’,….)

* S20 should exist in SUPPLIERS.S#


DML – UPDATE Statement

Syntax:
UPDATE table
SET column = scalar-expression [, column = scalar-expression]
[WHERE search-condition]
DML – UPDATE Statement
Single Row Update
UPDATE PARTS
SET COLOR =‘YELLOW’
WEIGHT = WEIGHT – 5
CITY = NULL
WHERE P# = ‘P2’

Multiple row Update


UPDATE SUPPLIER
SET STATUS = 2 STATUS WHERE CITY = ‘MADRAS’
DML – UPDATE Statement

Update with a subquery


UPDATE SHIPMENT
SET QTY = 0 WHERE ‘LONDON = (SELECT CITY FROM SUPPLIER
WHERE SUPPLIER.S = SHIPMENT.S#)
DML – UPDATE Statement
Update with Referential Integrity

UPDATE SHIPMENTS SET S# =‘S20’ WHERE … SUPPLIERS.S# should have an


entry S20

UPDATE SUPPLIERS SET S# = ‘S20’ WHERE S# = ‘S1’


DML – DELETE Statement

Syntax:
DELETE FROM table [WHERE condition]

Single row delete


DELETE FROM SUPPLIER WHERE S# = ‘S5’
DML – DELETE Statement
Multiple row delete
DELETE FROM SHIPMENT WHERE QTY > 300

Delete with a subquery


DELETE FROM SHIPMENT WHERE ‘MADRAS’ = (SELECT CITY FROM
SUPPLIER WHERE SUPPLIER.S# = SHIPMENT.S#)
DML – DELETE Statement
Delete with Referential Integrity

DELETE FROM SUPPLIERS WHERE S# = ‘S1’

* Execution depends on DELETE RULE – CASCADE, RESTRICT OR SET


NULL
Host Variables

MOVE 2120 TO WS-EMPNO


EXEC SQL
SELECT EMPNO, LASTNAME,SEX
INTO :WS-EMPNO: :WS-LAST:ws-SEX
FROM EMPLOYEE
WHERE EMPNO= : ws-EMPNO
END-EXEC
COBOL Host Variables

•All COBOL host variables must be explicitly declared in the DATA DIVISION.
• A colon ( : ) must precede all host variables in an SQL statement
• The names of the host variables must be unique within the program. Host
variable names can be qualified with a structure name to make them unique
• Host variables, other than indicator variables, cannot be defined as arrays.
An OCCURS clause must only be specified when defining an indicator
structure.
SQL and COBOL Data types

•SMALLINT PIC S9(04) COMP


• INTEGER PIC S9(09) COMP
• DECIMAL(p.s) PIC S9(P-S)V9(S)COMP 3
•CHAR (N) PIC X (n)
•VARCHAR(N) 01 VAR
•49VAR1 PICS9(04) COMP

•49 VAR2 PICX(n)


COBOL and SQL data types: Datetime

DATE PICX(10) - Format specified by an option


TIME PICX(08) - Format specifided by an option
TIMESTAMP PIC X (26)
String representation of timestamp has the format:
yyyy-mm-dd-hh.mm.ss.nnnnnn
DELETE … WHERE CURRENT OF

PERFORM OPEN-PARA
PERFORM FETCH-PARA.

PERFORM UNTIL SQLCODE =100


EXEC SQL
DELETE FROM EMPLOYEE
WHERE CURRENT OF CUREMP01
END-EXEC
PERFORM FETCH-PARA
END-PERFORM.
DECLARE … WITH HOLD

EXEC SQL
DECLARE cursor-name CURSOR WITH HOLD FOR
SELECT column-name-list
FROM table-name
WHERE search-condition
FOR UPDATE OF column-name
END-EXEC
WHENEVER

EXEC SQL
WHENEVER condition action
END-EXEC

condition : SQLWARNING
SQLERROR
NOT FOUND
action : CONTINUE
GOTO or GO TO procedure/section
Dynamic SQL

Statement:
Acquired during execution,and function can
vary and can be done to different tables and
columns
Bind: One single statement

At statement execution
Access strategy not saved..
Static SQL vs. Dynamic SQL

Statement:
Static : Object and Action known
Dynamic : Object or Action not known
Bind:
Static : is bound once
Dynamic : is bound every time.
Coding Dynamic SQL

• Translate the input data into a SQL statement


• Prepare the SQL statement to execute
• Execute the SQL statement
• Process the information returned
• Handle SQL return codes
EXECUTE IMMEDIATE

Prepare and Execute the SQL statement present in


theCOBOL host varilable WS-STMT
MOVE ‘DELETE FROM EMPLOYEE’ TO WS-STMT-TEXT
MOVE 50 TO WS-STMT-LEN
EXEC SQ
EXECUTE IMMEDIATE :WS-STMT
END-EXEC.
Parameters Markers
Prepare and Execute
Non-Qualified Objects : DATABASE (271)

Operation Privilege of Authority required

CREATE Any of : CREATADBA system authority


CREATEDBA system authority
SYSADM or SYSCTRL

ALTER Any of: DROP on the database


DBADM or DBCTRL authority for the database
SYSADM or SYSCTRL
Ownership of the database

DROP Any of: DROP on the database


DBADM or DBCTRL authority for the
database SYSADM or SYSCTRL
Non-Qualified Objects : DATABASE (271)

Operation Privilege of Authority required

CREATE Any of : CREATES on the database


DBASM or DBSTRL or
DBMAINT authority on the database
SYSADM or SYSCTRL

ALTER Any of: DBADM authority for the database


Ownership of the database
SYSADM or SYSCTRL

DROP Any of: DBADM authority for the database


Ownership of the database
SYSADM or SYSCTRL
Non-Qualified Objects: SYNONYM

Operation Privilege of Authority required

CREATE None to create on behalf of the primary authorization ID or


any secondary authorization ID. SYSADM or SYSCTRL for
others.

ALTER There is no ALTER on SYNONYMS

DROP Ownership of the Synonym


STATIC DDL : Qualified Objects

TABLE INDEX VIEW ALIAS

The privilege set of the plan/package owner are


checked or authorization.

If the qualifier for the object is not the same as the


owner of the object, additional privileges are
needed to CREATE each object
STATIC DDL : Qualified Objects

TABLE INDEX VIEW ALIAS

The privilege set of the plan/package owner are


checked or authorization.

If the qualifier for the object is not the same as the


owner of the object, additional privileges are
needed to CREATE each object
OWNER Vs CREATOR : Part I

SET CURRENT SQLID = ‘KING’


CREATOR

CREATE TABLE PRINCE.EMPLOYEE


( …… . . ) IN MYDB.MYTS;

OWNER
OWNER Vs CREATOR : Part II

SET CURRENT SQLID = ‘KING’


CREATOR
OWNER
CREATE TABLE EMPLOYEE
( …… . . ) IN MYDB.MYTS;

If the qualifier is not specified, for STATIC DDL, the ID named in the
QUALIFER parameter at the time of BIND is the OWNER. If no qualifier
is supplied, the owner of the plan/package is the OWNER of the object
Qualified Objects : TABLE

CREATE Any of : CREATAB privilege for the


database DBADM*, DBCTRL* or
DBMANT* authority on the database
SYSADM* or SYSCTRL

ALTER Any of : ALTER table on the database


Ownership of the table DBADM authority
on the database SYSADM or SYSCTRL

DROP Any of: Ownership of the table DBADM


authority on the database SYSADM or
SYSCTRL
Qualified Object : INDEX

Operation Privilege or Authority required

CREATE Any of : INDEX privilege on the table


Ownership of the table
DBADM* authority on the database
containing the table SYSADM* or SYSCTRL

ALTER Any of : Ownership of the index


Ownership of the table on which the index is
defined DBADM authority on the database
SYSADM or SYSCTRL

DROP Any of : Ownership of the index


DBADM authority on the database
SYSADM or SYSCTRL
Qualified Objects : VIEW

Operation Privilege or Authority required

CREATE Any of :SELECT Privilege on the table or view


Ownership of the table or view
DBADM authority for the database (for table)
SYSADM*
SYSCTRL (for catalog tables only)

ALTER There isnot ALTER on views

DROP Any of : Ownership of the view


SYSADM or SYSCTRL
Qualified Objects : ALIAS

Operation Privilege or Authority required

CREATE Any of :CREATEALILAS Privilege


SYSADM* or SYSCTRL

ALTER There is not ALTER on ALIASes

DROP Any of : Ownership of the alias


SYSADM or SYSCTRL
OWNER Vs CREATOR : Part III

TABLE INDEX ALIAS

SET CURRENT SQLID = ‘KING’ ;

CREATE TABLE G1.EMPLOYEE


( ……. . . ) IN MYDB.MYTS;
VIEW : A Security Mechanism

CREATE VIEW TRAINING


AS SELECT * FROM EMPLOYEE
WHERE DEPT = ‘TRAINING’ ;

GRANT SELECT, UPDATE(NAME)


ON TRAINING TO TRAINER ;
• View Limits the Data that is visible
• Grant limits data column that can be changed
DB2 UTILITIES
DB2 Utilities

» CHECK
» COPY
» DSN1COPY
» LOAD
» MERGECOPY
» MODIFY
» QUIESCE
» RECOVER
» REORG
» REPAIR
» RUNSTATS
» STOSPACE
LOAD Utility

Used to load data into one or more tables

Input:

LOAD DATA statement describing the data to be loaded

File containing data
Output

Loaded table or partition

Discard file of rejected records

Summary reports of errors encountered
LOAD Utility

Features


Automatic data conversion between compatible
data types

Data loaded in the sequence presented; no sort
invoked

Indexes built; duplicates checked
LOAD Utility

Phase Flow:

UTILINIT

RELOAD

SORT

BUILD

INDEXVAL

ENFORCE

DISCARD

REPORT
LOAD Utility

Example:
LOAD DATA INDDN(SYSREC)
RESUME YES
ENFORCE CONSTRAINTS
INTO TABLE TRGD55.PROJ
(PROJNO POSITION(1) CHAR(6),
PROJNAME POSITION(8) VARCHAR,
DEPTNO POSISION(33) CHAR(3))

Data File contains : 3


1 8 3
PROJ01 08training TRG
PROJ02 07Support SSG
REORG Utility


Reorganizes tablespace to reclaim fragmented space
and imporve access performance

Alter the physical space parameters for the
tablespace

Unload data in a format acceptable by the LOAD
utility

Reorganize tablespace or a partition
REORG Utility

Input:

Name of tablespace or partition or index to be
reorganized

Output:

Reorganized tablespace and / or indexed

Table data in LOAD format
REORG Utility

Phase Flow:


UTILINIT

UNLOAD

RELOAD

SORT

BUILD

UTILTERM
RUNSTATS Utility


Gathers information about data in table spaces and
indexes and updates DB2 catalog.


Use RUNSTATS when

A table is loaded

A table is reorganized

An index is created

Extensive modifications done on table space
RUNSTATS Utility

Input

Tablespace for which stastics is to tbe
updated / reported

Output:

Report containing new statistics

Updated DB2 catalog tables
RUNSTATS Utility

Phase Flow:


UTILINIT

RUNSTATS

UTILTERM
COPY Utility


Creates backup copies of a
tablespace or s single
partition

Reset copy pending status

Two types: Full image copy,
Incremental image copy
COPY Utility

Input:

Name of tablespace or partition to be
copied
Output

Asequential dataset containing the
image copy

SYSIBM.SYSCOPY updated

Copy pending status reset
UNLOAD Program

An IBM supplied program that unloads


data from a table in the LOAD utility
format

A WHERE clause can be supplied
to selectively unlaod rows

Output:

Sequential data set containing the
unloaded data

Load control statements
UNLOAD Program

Sample JCL
Sample Utilit JCL
eds.com
Contact information or Web site URL can be added here
Download the new PowerPoint presentation tutorial at:
http://infocentre.eds.com/workplace/how/present/present_main.html
DDL – CREATE Storage Group

Syntax:
CREATESTOGROUP Stogroup-name
VOLUMES (vol1, vol2,…)
VCAT catalog–name
(PASSWORD password)

CREATE STOGROUP TRG1T01


VOLUMES (DBPK01, DBPK02)
VCAT DB220TRG

 
DDL – ALTER Storage Group

Syntax:
ALTER STOGROUP stogroup-name
ADD VOLUMES ( vol4, vol5, …)
REMOVE VOLUMES (vol1, vol2, . . . )

ALTER STOGROUP TRG1T01


ADD VOLUMES (DBPK03)
REMOVE VOLUMES (DBPK01)
DDL – CREATE DATABASE

Syntax:
CREATE DATABASE database–name
(STOGROUP stogroup–name)
(BUFFERPOOL bufferpool–name)

CREATE DATABASE TRG1T01


STOGROUP TRG1T01
BUFFERPOOL BP0
DDL – CREATE TABLESPACE
Syntax :
CREATE TABLESPACE tablespace–name
IN database-name
USING STOGROUP stogroup – name
PRIQTY qty
SECQTY qty
ERASE YES/NO
LOCKSIZE ANY/PAGE/TABLESPACE/TABLE
BUFFERPOOL BPO/BP1/BP2/BP32K
CLOSE YES/NO DSETPASS password
FREEPAGE <amount> PCTFREE <amount>
DDL – CREATE TABLESPACE Parameters

PRIQTY & SECQTY

* PRIQTY amount of physical storage allocated when


tablespace is created

* SECQTY space taken amount of data in tablespace grows

* specified in KB
DDL – CREATE TABLESPACE Parameters

ERASE:

* Indicates whether the DB2 defined datasets


are to be erased when tablespace is
dropped

LOCKSIZE:

* Indicates type of locking


(Page/Tablespace/Table/DB2 decided)
DDL – CREATE TABLESPACE Parameters

BUFFERPOOL:

* Buffer pool to be associated with tablespace


* Default value is default buffer pool of database

CLOSE:

* Indicates whether data sets associated with tablespace;should be closed when there are no
current users of tablespace

* Default is YES
DDL – CREATE TABLESPACE Parameters

FREEPAGE:

* Specified number of pages after which


a completely empty page is available
* Default is FREEPAGE 0

PCTFREE:

* Specifies percentage of each page


available for future inserts
* Default is PCTFREE 5
DDL – CREATE TABLESPACE
Example:

CREATE TABLESPACE
IN DSN8DP2AP
USING STOGROUP DSNS6200
PRIQTY 12
SECQTY 12
ERASE NO
LOCKSIZE ANY
CLOSE YES
BUFFERPOOL BP0
DDL – ALTER TABLESPACE

ALTER TABLESPACE tablespace-name


BUFFERPOOL BP0/BP1/BP2
LOCKSIZE ANY/PAGE/TABLESPACE/TABLE
CLOSE YES/NO
DSETPASS password
FREEPAGE amount
PRIQTY qty
SECQTY qty
ERASE YES/NO
DDL- CREATE TABLE

Syntax : (Format 1)

CREATE TABLE tablename


(column-definition [, column-definition] . . .
[, primary-key-definition]
[, foreign-key-definition
[, foreign-key-definition]. . .])
[other-parameters] )
[ IN databasename.tablespacename /
IN DATABASE databasename]
DDL- CREATE TABLE

Syntax : (Format 2)

CREATE TABLE tablename


LIKE existing-tablename
DDL-CREATE TABLE

COLUMN- definition:

colname coltype (NOT NULL/ NULL / NOT NULL


WITH DEFAULT)
Primary-key definition:

PRIMARY KEY(colname1,colname2,…)
DDL- CREATE TABLE

foreign-key definition:

FOREIGN KEY [constraint-name]


(colname1 [, colname2] . . .)
REFERENCES base-table
[ ON DELETE RESTRICT / CASCADE /
SET NULL]
DDL-CREATE TABLE

Other parameters:

EDITPROC : edit routine for table

VALIDPROC : validation routine for table


DDL – CREATE TABLE

Example

CREATE TABLE SUPPLIER


(S# CHAR(5) NOT NULL,
SNAME CHAR(20) NOT NULL,
STATUS SMALLINT NOT NULL WITH DEFAULT
CITY CHAR(15) NOT NULL WITH DEFAULT
PRIMARY KEY (S#) )
IN TRG1T01.DSN8D2AP
DDL – ALTER TABLE
Syntax:

ALTER TABLE tablename


ADD column-definition
VALIDPROC program-name NULL
primary-key-definition
referential-constraint
CRC? PRIMARY KEY
CRC? FOREIGN KEY constraint-name
DDL – CREATE INDEX
Syntax:

CREATE (UNIQUE) INDEX indexname


ON tablename (colname [ASC / DESC], . …)
[USING STOGROUP stogroupname
PRIQTY qty
SECQTY qty
ERASE YES/NO]
[CLUSTER] [SUBPAGES amount]
[BUFFERPOOL BP0/BP1/BP2]
[CLOSE YES/NO] [DSETPASS password]
[PCTFREE amount] [ FREEPAGE amount]
DDL- CREATE INDEX
Example:

CREATE UNIQUE INDEX XS


ON SUPPLIER (S#)
USING STOGROUP TRG1TO1
PRIQTY 16
SECQTY 4
ERASE NO
DDL – ALTER INDEX

Syntax :

ALTER INDEX index-name


BUFFERPOOL BPO/BP1/BP2
CLOSE YES/NO
DSETPASS password
FREEPAGE qty PCTFREE qty
USING STOGROUP stogroupname
PRIQTY amount SECQTY amount
ERASE YES/NO
DDL – CREATE VIEW

Syntax:

CREATE VIEW view-name


(column-name, . . .)
As subselect
WITH CHECK OPTION
DDL – CREATE SYNONYM

Syntax :

CREATE SYNONYM synonym


FOR auth-id.table-name
DDL – DROP Statement
Syntax:

DROP object-type objectname

Example

DROP DATABASE TRG1TO1


DROP TABLE SUPPLIER
DROP INDEX XS
DDL- DROP Dependencies
DROP DEPENDENCIES
SQL- DML

DATA
MANIPULATION
LANGUAGE
DML Overview
DML verbs are:

* SELECT - Retrieves data


* UPDATE - Changes value(s)
* DELETE - Remove row(s)
* INSERT - Adds new row(s)
will be explained using an example
DML – SELECT Select Overview

Select statement is used to assess data from one or more tables:


(a) Simple Queries (f ) Aggregate
(b) Qualified retrieval functions
(c) Retrieval with ordering (g) Grouping
(d) Join enquiries (h) Union
(e) Subqueries
DML – Supplier Parts Example

ko m m
ko ko ko
m k
ko m
o
DML – SELECT Statement

Syntax:

SELECT [ ALL | DISTINCT ] scalar- expression


FROM table(s)
[WHERE search-condition]
[GROUP BY column(s) ]
[HAVING search-condition]
[ORDER BY column(s) ]
DML – SELECT Statement

Scalar Expressions
(LENGTH (SNAME) – 1 * 2
SALARY + COMMISSION + BONUS

Search Condition
(SUBSTR (SNAME,1,3) = ‘VIJ’
AND
CITY = ‘MADRAS’
DML- SELECT Statement

(a) Simple Queries

• SELECT P# FROM SHIPMENTS

• SELECT SHIPMENTS. P# FROM SHIPMENTS

• SELECT DISTINCT P# FROM SHIPMENTS


DML – SELECT Statement
(b) Simple Queried (Contd…)

• SELECT * FROM SUPPLIER

• SELECT P#, ‘Weight in grams = ‘,


WEIGHT * 454 FROM PARTS
DML – SELECT Statement

(b) Qualified Retrieval – using WHERE Clause

• SELECT S =
FROM SUPPLIERS
WHERE CITY = ‘MADRAS’
AND STATUS > 20;
DML – SELECT Statement

(b) Qualified Retrieval – Using BETWEEN predicate

* SELECT P#, PNAME, COLOR, WEIGHT,


CITY FROM PARTS
WHERE WEIGHT BETWEEN 16 AND 19

* SELECT P#,PNAME, COLOR, WEIGHT,


CITY FROM PARTS
WHERE WEIGHT NOT BETWEEN 16 AND 19
DML – SELECT Statement

(b) Qualified Retrieval – Using IN predicate

* SELECT P#, PNAME, COLOR, WEIGHT,CITY


FROM PARTS
WHERE WEIGHT IN (12,16,17)
DML – SELECT Statement

(b) Qualified Retrieval – Using LIKE predicate

•Used tosearch for strings that have a certain pattern


•% stands for any sequence of n characters
•- stands for any single character
•SELECT P#, PNAME, COLOR, WEIGHT, CITY
FROM PARTS
WHERE PNAME LIKE ‘C8’
DML – SELECT Statement

© Retrieval with Ordering


•SELECT S#,STATUS FROM SUPPLIER WHERE
CITY=‘Madras’ ORDER BY STATUS DESC
ASC/DESC – Puts row in ascending of descending
order.Default is ASC
DML – SELECT statement
(d) JOIN QUERIES – Simple quijoin
•SELECT SUPPLIER.*, PARTS.* FROM SUPPLIER, PARTS WHERE
SUPPLIER.CITY = PARTS.CITY

•* In the absence of WHERE clause, the result is the cartesian product


of the tables in the FROM
DML – SELECT Statement

(d) JOIN queries – Greater – Than Join

* SELECT SUPPLIER.* PARTS.* FROM SUPPLIER, PARTS WHERE


SUPPLIER.CITY, PARTS.CITY
* Join criteria can have other operators like >=, <>, <.<=
DML – SELECT Statement

(d) JOIN queries – Selef – Join

•Jon of a table with itself


•SELECT FIRST.S#, SECOND.S# FROM SUPPLIER FIRST,SUPPLIER
SECOND WHERE FIRST.CITY = SECOND.CITY
•FIRST AND SECOND are Range Variables of Correlation Names
DML – SELECT Statement
(d) JOIN queries – Multi-table-joins

•SELECT DISTINCT SUPPLIER.CITY, PARTS.CITY FROM SUPPLIER,


SHIPMENTS, PARTS WHERE SUPPLIER.S# = SHIPMENTS.S# AND
SHIPMENTS.P# = PARTS.P#
• A maximum of 15 tables can be joined in an SQL statement
DML – SELECT statement

(e) Subqueries of Nested Selects

•Simple Subquery
•SELECT SNAME FROM SUPPLIER WHERE S# IN (SELECT S# FROM
SHIPMENT WHERE P# = ‘P2’)
DML – SELECT Statement

(e) Correlated subquery


•A nested SELECT statement referring back to columns in out SELECT
statements
• SELECT SNAME FROM SUPPLIER WHERE ‘P2’ IN (SELECT P# FROM
SUPPLIER WHERE S# = SUPLIER.S#)
DML- SELECT Statement

(e) Joins VERSUS Subquries


* A subquery can be converted to an equivalet join
* Joins are more efficient than subqueries in DB2
DML – SELECT Statement

(f) Existential Quantifier

* Used to test for existence of certain rows


* SELECT SNAME FROM SUPPLIER WHERE EXISTS (SELECT *
FROM SHIPMENT WHERE S# = SUPPLIER.S# AND P# = ‘P2’)
DML – SELECT Statement
(g) Aggregate or Column Functions

•Functions operate on collection of values in a column


•Count – number of values in the column
•SUM - sum of values in the column
•AVG - average of the values in the column
•MAX - largest value in the column
•MIN - smallest value in the column
DML – SELECT Statement

(g) Aggregate Function – Examples


•SELECT COUNT(*) FROM SUPPLIER
• SELECT SUM(QTY) FROM SHIPMENT WHERE P# = ‘P2’
DML – SELECT Statement
(h) Grouping

Partition or Groups the rows based on given criteria

* SELECT P#, SUM(QTY) FROM SHIPMENT GROUP BY P#


DML – SELECT Statement

(h) Grouping (Contd…)

* SELECT p#, SUM(QTY), MAX(QTY) FROM SHIPMENT WHERE S#


<> ‘S1’ GROUP BY P#
DML – SELECT Statement

(h) Grouping – HAVING Clause

•HAVING is to groups what WHERE is to rows


• SELECT P# FROM SHIPMENT GROUP BY P# HAVING COUNT(*) > 1
DML – SELECT Statement

UNION
Union operation on union-compatible sets of rows

•SELECT P# FROM PARTS WHERE WEIGHT > 16


UNION
SELECT.P# FROM SHIPMENT WHERE S# = ‘S2’
Dml – DATE / TIME Arithmetic
Duration:

Date duration: yyyymmdd


Time duration: hhmmss
Timestamp duration: yyyymmddhhmmssnnnnn
Microsecond duration: nnnnnn
Dml – DATE / TIME Arithmetic

Labeled Duration:
•N units

n : any numeric expression


Units : YEAR[S],
MONTHS[S],DAY[S],HOUR[S],MINUTE[S],SECONDS[S],MICROSECOND[S]
e.g., 3 YEARS, 90 DAYS, 1 MINUTE
Dml – DATE / TIME Arithmetic

Extraction of Date / Time Components:


•YEAR , MONTH, DAY
•HOUR,MINUTE,SECOND
•MICROSECOND
Dml – DATE / TIME Arithmetic

Conversions To ? From other Data Types:

•DATE, TIME, TIMESTAMP


•CHAR
•DAYS
DML– DATE / TIME Arithmetic

Special Registers:

•CURRENT TIMEZONE
•CURRENT DATE
•CURRENT TIME
•CURRENT TIMESTAMP
DML – DATE / TIME Arithmetic

Examples:

• DATE(‘8/17/1996’) – DATE(’10/28/1996’)
• START_DATE + 1 YEAR + 6 MONTS
• CURRENT TIMESTAMP + 1 SECOND
• START_TIME – END_TIME < 080000
DML – INSERT Statement

Syntax:

INSERT
INTO table[ (column [, column] …)]
Values (literal [,literal]….)

Or

INSERT
INTO table [ (column[, column] …)]
subquery
DML – INSERT Statement
Examples

INSERT
INTO PARTS (P#, CITY, WEIGHT)
VALUES (‘P7’, ‘CALCUTTA’, 24)

INSERT
INTO PARTS
VALUES (‘P8’,‘SPROCKET’,‘PINK’,14,‘SHIMLA’)
DML – INSERT Statement

Insert with a subquery

INSERT
INTO TEMP (P#, TOTQTY)
SELECT P#,SUM(QTY)
FROM SHIPMENT
GROUP BY P#
DML – INSERT Statement
Insert with Referential Integrity

•Referential constraint from SHIPMENTS.S# to SUPPLIERS.S#

INSERT
INTO SHIPMENTS.S#, P#, QTY)
VALUES (‘S20’,….)

* S20 should exist in SUPPLIERS.S#


DML – UPDATE Statement

Syntax:

UPDATE table
SET column = scalar-expression
[, column = scalar-expression]
[WHERE search-condition]
DML – UPDATE Statement

Single Row Update

UPDATE PARTS
SET COLOR =‘YELLOW’
WEIGHT = WEIGHT + 5
CITY = NULL
WHERE P# = ‘P2’

Multiple row Update

UPDATE SUPPLIER
SET STATUS = 2 * STATUS
WHERE CITY = ‘MADRAS’
DML – UPDATE Statement

Update with a subquery

UPDATE SHIPMENT
SET QTY = 0
WHERE ‘LONDON =
(SELECT CITY FROM SUPPLIER
WHERE SUPPLIER.S # =
SHIPMENT.S#)
DML – UPDATE Statement

Update with Referential Integrity

UPDATE SHIPMENTS
SET S# =‘S20’
WHERE …
SUPPLIERS.S# should have an entry S20

UPDATE SUPPLIERS
SET S# = ‘S20’
WHERE S# = ‘S1’
DML – DELETE Statement

Syntax:

DELETE FROM table [WHERE condition]

Single row delete

DELETE FROM SUPPLIER


WHERE S# = ‘S5’
DML – DELETE Statement
Multiple row delete

DELETE FROM SHIPMENT


WHERE QTY > 300

Delete with a subquery


DELETE FROM SHIPMENT
WHERE ‘MADRAS’ =
(SELECT CITY FROM SUPPLIER
WHERE SUPPLIER.S# =
SHIPMENT.S#)
DML – DELETE Statement
Delete with Referential Integrity

DELETE FROM SUPPLIERS


WHERE S# = ‘S1’

* Execution depends on DELETE RULE –


CASCADE, RESTRICT OR SET NULL

You might also like