You are on page 1of 137

DB2

eds
Electronic Data Systems Version 1.0

DB2
Volume I
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
Terminal
CICS
Terminal
TSO
Terminal
IMS/DC CICS TSO TSO
IMS
Batch
Application
IMS/DB DB2
IMS
Online
Application
TSO
Online
Application
TSO
Batch
Application
CAF
Application
CICS
Online
Application
IMS Databases DB2 Databases
MVS
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.



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

Attribute
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 table 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 Name Dept Join_Date
2000 Vijay 101 01/01/85
3000 Gupta 102 01/01/96
4000 Sridevi 103 01/02/95

Dept #
Primary Key of
Department table
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 do not
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


Join_date >= 1/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


01/02/95 4000
01/01/96 3000
01/01/85 2000
Join_Date Emp #
Project
Emp #
Join_date
JOIN
b2 a3
b1 a2
b1 a1
c3 b3
c2 b2
c1 b1
JOIN
c3 b3 a3
c2 b2 a2
c1 b1 a1
JOIN
OUTER INNER
LEFT OUTER FULL OUTER RIGHT OUTER
INNER 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
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
2000 Vijay 101 01/01/85 Marketing Chennai
3000 Gupta 102 01/01/96 Personnel Mumbai
4000 Sridevi 103 01/02/95 ? ?
? ? 104 ? Training Madras

DIVIDE
x b
y c
z a
y a
x a
Divide
y
x
a
UNION
Gupta 3000
Patel 2000
Name Emp #
Hari 5000
Guru 6000
Gupta 3000
Singh 2500
Name Emp #
Hari 5000
Gupta 3000
Singh 2500
Guru 6000
Gupta 3000
Patel 2000
Name Emp #
UNION
INTERSECTION


Project 1
Hari 5000
Guru 6000
Gupta 3000
Singh 2500
Name Emp #
Gupta 3000
Patel 2000
Name Emp #
Project 2
INTERSECTION
Gupta 3000
Name Emp #
DIFFERENCE
Gupta 3000
Patel 2000
Name Emp #
Project1
Hari 5000
Guru 6000
Gupta 3000
Singh 2500
Name Emp #
Project 2
Difference
Patel 2000
Name Emp #
CARTESIAN PRODUCT
c
b
a
y
x
PRODUCT
y b
y a
x b
y c
x c
x a
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
Physical
Representation
Logical Representation
DB2 Transformation
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
SPACE
PAGE
Data Records
Simple Tablespaces







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

Segmented Tablespaces

Table 1

Table 2

Table 3
Segment 1 Segment 2 Segment 3
Partitioned Tablespaces
Part 1 Part 2 Part 3 Part 4
Indexes
2 104
4 103
3 102
1 101
103
102
104
101
KEY
Position
Indexes : Terminology
Indexing Key Composite Key
Unique Index Non-Unique Index
Primary Index Secondary Index
Partitioning Index Clustering Index
B+ Trees


25
8 17 33 40
46 51 55 28 31 33 35 38 40 1 3 8 9 11 17 19 21 25
Root Node
Intermediate Nodes
Leaf NodesPointing
to Data Pages
Clustering Index
25
8 17 33 40
46 51 55 28 31 33 35 38 40 1 3 8 9 11 17 19 21 25
Data
Pages
Non-clustered Index Scan

25
8 17 33 40
46 51 55 28 31 33 35 38 40 1 3 8 9 11 17 19 21 25
Data
Pages
Stogroup

Dev 001
Dev 001
Dev 001
Dev 001
SG2
SG3
SG1
Database

Storage Groups
Table Space
Table Table
Table
Table Space
Index
Index
Bufferpools

4 KB Pages 32 KB Pages
DB2 System Objects
• Bufferpool
• EDM Pool ( Environment Descriptor
Manager )
• BSDS ( Bootstrap Dataset )
• Logs ( Active and Archive logs )
Data Types : String
String
Graphic Character
Variable Length Fixed Length Variable Length Fixed Length
Data Types : Datetime
Datetime
Timestamp Time Date
Data Types : Numeric
Numeric
Decimal Binary Integer Floating Point
Large Small
Large Small
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

End Transaction
All Changes “ DONE”
Begin Transaction

End Transaciton

All Changes“UNDONE”

SQL Command

SQL Command

COMMIT

SQL Command

SQL Command

COMMIT

ROLLBACK
Transactions : An example
Transaction

Withdraw 1000 from Account 1
Deposit 1000 from Account 2
Account 1
Balance = 2000
Account 2
Balance = 5000
Account 1
Balance = 1000
Account 2
Balance = 6000
Transaction : ACID Properties

ATOMICITY

CONSISTENCY

ISOLATION

DURABILITY

Lost Update Problem
User 1
Send 1000 units
Quantity = 2000
Quantity = 1000
Quantity = 4000
User 2
Receive 2000 units
Uncommited Read
User 1
Send 1000 units


ROLLBACK
Quantity = 2000
Quantity = 1000
Quantity = 3000
User 2
Receive 2000 units
Quantity = 2000
Incorrect Summary Problem


Roll # Marks Percentile
101
102
103
104
91
64
77
80
Read
all
the
rows
twice
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 ApplicationPrograms

– 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
User 1
User 2
Table 1
Table 2
LOCK
HELD
Lock
Requested
Lock
Held
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
DDL
Data Manipulation Language
DML
Data Control Language
DCL
Utilities

• LOAD

• UNLOAD

• REORG

• 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 - Operations

• 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





X X Synonym
X X X Table
X X X Index
X X X Tablespace
X X View
X X Database
X X X Storage Group
DROP ALTER CREATE
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,…)
foreign-key definition:

FOREIGN KEY [constraint-name]
(colname1 [, colname2] . . .)
REFERENCES base-table
[ ON DELETE RESTRICT / CASCADE /
SET NULL]
DDL- CREATE TABLE
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
Storage Group
Database
Synonym
Tables
Index
Table Space
Views Alias
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 – SELECT Statement

S# SNAME STATUS CITY S# P# QTY
S1 Arun 20 Madras S1 P1 300
S2 Rao 10 Hyderabad S1 P2 200
S3 Tarun 30 Hyderabad S1 P3 400
S4 Sanjay 20 Madras S1 P4 200
S5 Vinod 30 Calcutta S1 P5 100
S1 P6 100
P# PNAME COLOR WEIght CITY S2 P1 300
P1 Nut Red 12 Madras S2 P2 400
P2 Bolt Green 17 Hyderabad S3 P2 200
P3 Screw Blue 17 Bombay S4 P2 200
P4 Screw Red 14 Madras S4 P4 300
P5 Carn Blue 12 Hyderabad S4 P5 400
P6 Cog Green 19 Madras

PARTS
SUPPLIERS
SHIPMENTS
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
(d) JOIN queries – Self–Join

• Join 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) Sub queries of Nested Selects

• Simple Sub query

• SELECT SNAME FROM SUPPLIER
WHERE S# IN
( SELECT S# FROM SHIPMENT
WHERE P# = ‘P2’ )
DML – SELECT Statement
(e) Correlated sub query

• A nested SELECT statement referring back to columns
in outer SELECT statements

• SELECT SNAME FROM SUPPLIER
WHERE ‘P2’ IN
( SELECT P# FROM SUPPLIER
WHERE S# = SUPLIER.S# )
DML- SELECT Statement
(e) Joins VERSUS Sub queries

• A sub query can be converted to an equivalent join

• Joins are more efficient than sub queries 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 (Counted…)

• 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