db2-1

137
DB2 eds Electronic Data Systems Version 1.0

Upload: airish-sashidharan

Post on 16-Apr-2017

218 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: DB2-1

DB2

edsElectronic Data Systems Version 1.0

Page 2: DB2-1

DB2

Volume I

Page 3: DB2-1

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

Page 4: DB2-1

DB2 : Some History

 Research : System R

1983 : DB2 Version 1 Research : System R* Starburst 1995 : DB2 version 4

Page 5: DB2-1

DB2 and MVS

IMSTerminal

CICSTerminal

TSOTerminal

IMS/DC CICS TSO TSO

IMSBatch

Application

IMS/DB DB2

IMSOnline

Application

TSOOnline

Application

TSOBatch

Application

CAFApplication

CICSOnline

Application

IMS Databases DB2 DatabasesMVS

Page 6: DB2-1

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

Page 7: DB2-1

Relational Model

An overview

Page 8: DB2-1

Relational Model

• Relational Data StructureTable

 • Relational Data Integrity

Entity IntegrityReferential Integrity

 • Relational Data Manipulation

Relational Algebra

Page 9: DB2-1

Relational Data Structure.

Emp Name Age Sex Dept# Join_Date 2000 Vijay 33 M 101 01/01/853000 Gupta 24 M 102 01/01/851000 Sridevi 29 F 101 01/02/962500 Patel 29 M 103 01/01/88

Attribute

Page 10: DB2-1

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.

Page 11: DB2-1

Missing Values : NULL

Column Value-         Not Applicable -         Not Available Emp Name Project Join_Date2000 Vijay GE 01/01/853000 Gupta ? 01/01/964000 Sridevi HP 01/02/95

Page 12: DB2-1

Relational Data Integrity

• Primary Key-         Uniqueness-         Minimality

 • Alternate Key • Foreign Key

Page 13: DB2-1

Foreign KeyDepartment Dept Name

Location101 Marketing Chennai102 Personnel Mumbai103 Admin Chennai104 Training Chennai

Emp Name Dept Join_Date2000 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

Page 14: DB2-1

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 .

Page 15: DB2-1

Relational AlgebraRestrict Project Join DivideUnion 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

Page 16: DB2-1

RESTRICT

Emp Name Project Join_Date2000 Vijay GE 01/01/853000 Gupta ? 01/01/964000 Sridevi HP 01/02/95

Emp Name Project Join_Date3000 Gupta ? 01/01/96

Join_date >= 1/01/96

Page 17: DB2-1

ProjectEmp# NameProject Join_Date2000 Vijay GE 01/01/853000 Gupta ? 01/01/964000 Sridevi HP 01/02/95

01/02/95 4000

01/01/96 3000

01/01/85 2000

Join_DateEmp # ProjectEmp #

Join_date

Page 18: DB2-1

JOIN

b2a3

b1a2

b1a1

c3b3

c2b2

c1b1

JOIN

c3b3a3

c2b2a2

c1b1a1

JOIN

OUTERINNER

LEFT OUTER FULL OUTER RIGHT OUTER

Page 19: DB2-1

INNER JOIN Emp# Name Dept # Join_Date2000 Vijay 101 01/01/853000 Gupta 102 01/01/964000 Sridevi 103 01/02/95

Dept# Name Location101 Marketing Chennai102 Personnel Mumbai104 Training Chennai

Join on Dept #

Emp#Name Dept # Join_Date Name Location2000 Vijay 101 01/01/85Marketing Chennai3000 Gupta 102 01/01/96Personnel Mumbai

Page 20: DB2-1

Left Outer JOIN Emp# Name Dept Join_Date2000 Vijay 101 01/01/853000 Gupta 102 01/01/964000 Sridevi 103 01/02/95

Dept# Name Location101 Marketing Chennai102 Personnel Mumbai104 Training Chennai

Join on Dept #

Emp# Name Dept# Join_Date Name Location2000 Vijay 101 01/01/85 Marketing Chennai3000 Gupta 102 01/01/96 Personnel Mumbai4000 Sridevi 103 01/02/95 ? ?

Page 21: DB2-1

Right Outer JOIN Emp# Name Dept Join_Date2000 Vijay 101 01/01/853000 Gupta 102 01/01/964000 Sridevi 103 01/02/95

Dept# Name Location101 Marketing Chennai102 Personnel Mumbai104 Training Chennai

Join on Dept #Emp# Name Dept# Join_Date Name Location2000 Vijay 101 01/01/85 Marketing Chennai3000 Gupta 102 01/01/96 Personnel Mumbai ? ? 104 ? Training Madras

Page 22: DB2-1

Full Outer JOIN Emp# Name Dept Join_Date2000 Vijay 101 01/01/853000 Gupta 102 01/01/964000 Sridevi 103 01/02/95

Dept# Name Location101 Marketing Chennai102 Personnel Mumbai104 Training Chennai

Join on Dept #

Emp# Name Dept# Join_Date Name Location2000 Vijay 101 01/01/85 Marketing Chennai3000 Gupta 102 01/01/96 Personnel Mumbai4000 Sridevi 103 01/02/95 ? ? ? ? 104 ? Training Madras

Page 23: DB2-1

DIVIDE

xb

yc

za

ya

xa

Divide

y

x

a

Page 24: DB2-1

UNION

Gupta3000

Patel2000

NameEmp #

Hari5000

Guru6000

Gupta3000

Singh2500

NameEmp #Hari5000

Gupta3000Singh2500

Guru6000

Gupta3000

Patel2000 NameEmp #

UNION

Page 25: DB2-1

INTERSECTIONProject 1

Hari5000

Guru6000

Gupta3000

Singh2500

NameEmp #

Gupta3000

Patel2000

NameEmp #

Project 2INTERSECTION

Gupta 3000

NameEmp #

Page 26: DB2-1

DIFFERENCE

Gupta3000

Patel2000

NameEmp #

Project1

Hari5000

Guru6000

Gupta3000

Singh2500

NameEmp #

Project 2 Difference

Patel 2000

NameEmp #

Page 27: DB2-1

CARTESIAN PRODUCT

c

b

a

y

x

PRODUCTyb

ya

xb

yc

xc

xa

Page 28: DB2-1

Relational Model : Some Advantages

* Easy to Understand 

* Elimination of need to preplan

“ HOW “ to get to data 

* Flexibility

Page 29: DB2-1

Data Management in DB2

An Introduction

Page 30: DB2-1

DB2 Data Objects 

• Storage Group• Databases• Tablespaces• Indexes• Bufferpools• EDM pool• BSDS• Logs

Page 31: DB2-1

DB2 Tablespaces

Physical Representation

Logical Representation

DB2 Transformation

Page 32: DB2-1

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

Page 33: DB2-1

Simple Tablespaces

Page 1 Page 2

Table 2 - Row CTable 3 - Row NTable 2 - Row DTable 1 - Row WTable 2 - Row ETable 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

Page 34: DB2-1

Segmented Tablespaces

Table 1 Table 2 Table 3

Segment 1 Segment 2 Segment 3

Page 35: DB2-1

Partitioned Tablespaces

Part 1 Part 2 Part 3 Part 4

Page 36: DB2-1

Indexes

2104

4103

3102

1101

103

102

104

101

KEY Position

Page 37: DB2-1

Indexes : Terminology

Indexing Key Composite KeyUnique Index Non-Unique IndexPrimary Index Secondary IndexPartitioning Index Clustering Index

Page 38: DB2-1

B+ Trees

25

8 17 33 40

46 51 5528 31 33 35 38 401 3 8 9 11 17 19 21 25

Root Node

Intermediate Nodes

Leaf NodesPointing to Data Pages

Page 39: DB2-1

Clustering Index25

8 17 33 40

46 51 5528 31 33 35 38 401 3 8 9 11 17 19 21 25

DataPages

Page 40: DB2-1

Non-clustered Index Scan

25

8 17 33 40

46 51 5528 31 33 35 38 401 3 8 9 11 17 19 21 25

DataPages

Page 41: DB2-1

Stogroup

Dev 001

Dev 001

Dev 001

Dev 001

SG2

SG3

SG1

Page 42: DB2-1

Database

Storage Groups

Table Space

Table Table

Table

Table Space

Index

Index

Page 43: DB2-1

Bufferpools4 KB Pages 32 KB Pages

Page 44: DB2-1

DB2 System Objects

• Bufferpool• EDM Pool ( Environment Descriptor Manager )• BSDS ( Bootstrap Dataset )• Logs ( Active and Archive logs )

Page 45: DB2-1

Data Types : String

String

GraphicCharacter

Variable LengthFixed LengthVariable LengthFixed Length

Page 46: DB2-1

Data Types : Datetime

Datetime

TimestampTime Date

Page 47: DB2-1

Data Types : Numeric

Numeric

DecimalBinary Integer Floating Point

LargeSmall LargeSmall

Page 48: DB2-1

DB2 Functions and Components

An Introduction

Page 49: DB2-1

DB2 Catalog

Data about data DB2 is managing – “ Metadata

Stored in DB2 Tables

Can be accessed in the same way as user data

Page 50: DB2-1

TransactionsBegin Transaction

End Transaction All Changes “ DONE”

Begin Transaction

End Transaciton

All Changes“UNDONE”

SQL Command

SQL Command

COMMIT

SQL Command

SQL Command

COMMIT

ROLLBACK

Page 51: DB2-1

Transactions : An example

Transaction

Withdraw 1000 from Account 1Deposit 1000 from Account 2

Account 1Balance = 2000

Account 2Balance = 5000

Account 1Balance = 1000

Account 2Balance = 6000

Page 52: DB2-1

Transaction : ACID Properties

ATOMICITY

CONSISTENCY

ISOLATION

DURABILITY

Page 53: DB2-1

Lost Update Problem

User 1

Send 1000 units

Quantity = 2000

Quantity = 1000

Quantity = 4000

User 2

Receive 2000 units

Page 54: DB2-1

Uncommited Read

User 1

Send 1000 units

ROLLBACK

Quantity = 2000

Quantity = 1000

Quantity = 3000

User 2

Receive 2000 units

Quantity = 2000

Page 55: DB2-1

Incorrect Summary Problem

Roll # Marks Percentile

101

102

103

104

91

64

77

80 Read all the

rowstwice

Page 56: DB2-1

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 neededMode : How severe is the lock

Page 57: DB2-1

Lock : Object

PAGE or ROW

Great concurrencyMore locking overhead

TABLE or TABLESPACE

Less locking overhead More data is restricted

Page 58: DB2-1

Lock : Duration

Different options for ApplicationPrograms

– ACQUIRE/RELEASE

– ISOLATION LEVEL

Page 59: DB2-1

Lock : Mode

Shared - Data is being Read Other users can read the same

data

Exclusive - Data is being changed No other users allowed

Page 60: DB2-1

DEADLOCK

User 1 User 2

Table 1 Table 2

LOCKHELD

Lock Requested

Lock Held

Page 61: DB2-1

Failures

* Hardware Failure

* Program Failure

* Natural Calamity

Page 62: DB2-1

Backing up data

* IMAGE COPY* FULL* INCREMENTAL

* MERGECOPY* FUZZYCOPY

Page 63: DB2-1

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 ]

Page 64: DB2-1

Recovery

* RECOVER UtilityTablespace is the unit of recovery

* Point of time recovery

* Disaster Recovery

Page 65: DB2-1

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.

Page 66: DB2-1

Security

• Outside Db2- RACF

• Within DB2- Privileges - Administrative Authorities

Page 67: DB2-1

Application Programming Interface

SQL – Structured Query Language

Embedded SQL DB2 Interactive (DB2l)

SQL

Data Definition LanguageDDL

Data Manipulation LanguageDML

Data Control LanguageDCL

Page 68: DB2-1

Utilities

• LOAD

• UNLOAD

• REORG

• RUNSTATS

Page 69: DB2-1

SQL - DDL

DATA

DEFINITION

LANGUAGE

Page 70: DB2-1

SQL – Structured Query Language

SQL

DDL DML DCL

Page 71: DB2-1

DDL – DB2 Objects

• Storage Group• Database• Tablespace• Table• Index• View• Synonym

Page 72: DB2-1

DDL - Operations

• CREATE - Defines a new object

• ALTER - Modifies an object

• DROP - Deletes a defined object

• Entered interactively or embedded in application programs.

Page 73: DB2-1

DDL – OBJECTS vs OPERATIONS

XXSynonym

XXXTable

XXXIndex

XXXTablespace

XXView

XXDatabase

XXX Storage Group

DROPALTERCREATE

Page 74: DB2-1

DDL – CREATE Storage Group

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

CREATE STOGROUP TRG1T01 VOLUMES (DBPK01, DBPK02) VCAT DB220TRG

 

Page 75: DB2-1

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)

Page 76: DB2-1

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

CREATE DATABASE TRG1T01 STOGROUP TRG1T01 BUFFERPOOL BP0

Page 77: DB2-1

DDL – CREATE TABLESPACESyntax : 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>

Page 78: DB2-1

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

Page 79: DB2-1

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)

Page 80: DB2-1

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

Page 81: DB2-1

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

Page 82: DB2-1

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

Page 83: DB2-1

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

Page 84: DB2-1

DDL- CREATE TABLESyntax : (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]

Page 85: DB2-1

DDL- CREATE TABLE

Syntax : (Format 2)

CREATE TABLE tablename LIKE existing-tablename

Page 86: DB2-1

DDL-CREATE TABLECOLUMN- definition: colname coltype (NOT NULL/ NULL / NOT NULL WITH DEFAULT)Primary-key definition:

PRIMARY KEY(colname1,colname2,…)

Page 87: DB2-1

foreign-key definition: FOREIGN KEY [constraint-name] (colname1 [, colname2] . . .) REFERENCES base-table

[ ON DELETE RESTRICT / CASCADE / SET NULL]

DDL- CREATE TABLE

Page 88: DB2-1

DDL-CREATE TABLE

Other parameters: EDITPROC : edit routine for table

VALIDPROC : validation routine for table

Page 89: DB2-1

DDL – CREATE TABLEExample

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

Page 90: DB2-1

DDL – ALTER TABLESyntax:

ALTER TABLE tablename ADD column-definition VALIDPROC program-name NULL primary-key-definition referential-constraint CRC? PRIMARY KEY CRC? FOREIGN KEY constraint-name

Page 91: DB2-1

DDL – CREATE INDEXSyntax:

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]

Page 92: DB2-1

DDL- CREATE INDEXExample:

CREATE UNIQUE INDEX XS ON SUPPLIER (S#) USING STOGROUP TRG1TO1 PRIQTY 16 SECQTY 4 ERASE NO

Page 93: DB2-1

DDL – ALTER INDEXSyntax :

ALTER INDEX index-name BUFFERPOOL BPO/BP1/BP2 CLOSE YES/NO DSETPASS password FREEPAGE qty PCTFREE qty USING STOGROUP stogroupname

PRIQTY amount SECQTY amountERASE YES/NO

Page 94: DB2-1

DDL – CREATE VIEW

Syntax:

CREATE VIEW view-name (column-name, . . .) As subselect WITH CHECK OPTION

Page 95: DB2-1

DDL – CREATE SYNONYMSyntax :

CREATE SYNONYM synonymFOR auth-id.table-name

Page 96: DB2-1

DDL – DROP StatementSyntax:

DROP object-type objectname Example

DROP DATABASE TRG1TO1 DROP TABLE SUPPLIER DROP INDEX XS

Page 97: DB2-1

DDL- DROP DependenciesDROP DEPENDENCIES

Storage Group

Database

Synonym

Tables

Index

Table Space

Views Alias

Page 98: DB2-1

SQL- DML

DATA MANIPULATION

LANGUAGE

Page 99: DB2-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

Page 100: DB2-1

DML – SELECT Select OverviewSelect 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

Page 101: DB2-1

DML – SELECT Statement

S# SNAME STATUS CITY S# P# QTYS1 Arun 20 Madras S1 P1 300S2 Rao 10 Hyderabad S1 P2 200S3 Tarun 30 Hyderabad S1 P3 400S4 Sanjay 20 Madras S1 P4 200S5 Vinod 30 Calcutta S1 P5 100

S1 P6 100P# PNAME COLOR WEIght CITY S2 P1 300P1 Nut Red 12 Madras S2 P2 400P2 Bolt Green 17 Hyderabad S3 P2 200P3 Screw Blue 17 Bombay S4 P2 200P4 Screw Red 14 Madras S4 P4 300P5 Carn Blue 12 Hyderabad S4 P5 400P6 Cog Green 19 Madras

PARTS

SUPPLIERS SHIPMENTS

Page 102: DB2-1

DML – SELECT StatementSyntax:

SELECT [ ALL | DISTINCT ] scalar- expressionFROM table(s)[WHERE search-condition][GROUP BY column(s) ][HAVING search-condition][ORDER BY column(s) ]

Page 103: DB2-1

DML – SELECT Statement

Scalar Expressions (LENGTH (SNAME) – 1 * 2 SALARY + COMMISSION + BONUS Search Condition (SUBSTR (SNAME,1,3) = ‘VIJ’ AND

CITY = ‘MADRAS’

Page 104: DB2-1

DML- SELECT Statement

(a) Simple Queries

• SELECT P# FROM SHIPMENTS

• SELECT SHIPMENTS. P# FROM SHIPMENTS

• SELECT DISTINCT P# FROM SHIPMENTS

Page 105: DB2-1

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

• SELECT * FROM SUPPLIER

• SELECT P#, ‘Weight in grams = ‘, WEIGHT * 454 FROM PARTS

Page 106: DB2-1

DML – SELECT Statement

(b) Qualified Retrieval – using WHERE Clause

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

Page 107: DB2-1

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

Page 108: DB2-1

DML – SELECT Statement

(b) Qualified Retrieval – Using IN predicate

* SELECT P#, PNAME, COLOR, WEIGHT,CITY FROM PARTS WHERE WEIGHT IN (12,16,17)

Page 109: DB2-1

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

Page 110: DB2-1

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

Page 111: DB2-1

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’ )

Page 112: DB2-1

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# )

Page 113: DB2-1

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

Page 114: DB2-1

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’ )

Page 115: DB2-1

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

Page 116: DB2-1

DML – SELECT Statement

(g) Aggregate Function – Examples

• SELECT COUNT(*) FROM SUPPLIER

• SELECT SUM(QTY) FROM SHIPMENT WHERE P# = ‘P2’

Page 117: DB2-1

DML – SELECT Statement

(h) Grouping

• Partition or Groups the rows based on given criteria

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

Page 118: DB2-1

DML – SELECT Statement

(h) Grouping (Counted…)

• SELECT p#, SUM(QTY), MAX(QTY) FROM SHIPMENT WHERE S# <> ‘S1’ GROUP BY P#

Page 119: DB2-1

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

Page 120: DB2-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’

Page 121: DB2-1

DML – DATE / TIME ArithmeticDuration:

Date duration: yyyymmdd

Time duration: hhmmss

Timestamp duration: yyyymmddhhmmssnnnnn

Microsecond duration: nnnnnn

Page 122: DB2-1

DML – DATE / TIME Arithmetic

Labeled Duration:

• n units

n : any numeric expressionUnits : YEAR[S], MONTHS[S],DAY[S],HOUR[S], MINUTE[S],SECONDS[S],MICROSECOND[S]

e.g., 3 YEARS, 90 DAYS, 1 MINUTE

Page 123: DB2-1

DML – DATE / TIME ArithmeticExtraction of Date / Time Components:

• YEAR , MONTH, DAY

• HOUR,MINUTE,SECOND

• MICROSECOND

Page 124: DB2-1

DML – DATE / TIME Arithmetic

Conversions To / From other Data Types:

• DATE, TIME, TIMESTAMP

• CHAR

• DAYS

Page 125: DB2-1

DML– DATE / TIME Arithmetic

Special Registers:

•CURRENT TIMEZONE•CURRENT DATE•CURRENT TIME•CURRENT TIMESTAMP

Page 126: DB2-1

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

Page 127: DB2-1

DML – INSERT StatementSyntax:

INSERTINTO table[ (column [, column] …)]Values (literal [,literal]….)

Or

INSERTINTO table [ (column[, column] …)]subquery

Page 128: DB2-1

DML – INSERT StatementExamples

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

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

Page 129: DB2-1

DML – INSERT Statement

Insert with a subquery

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

Page 130: DB2-1

DML – INSERT StatementInsert with Referential Integrity

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

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

* S20 should exist in SUPPLIERS.S#

Page 131: DB2-1

DML – UPDATE Statement

Syntax:

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

Page 132: DB2-1

DML – UPDATE StatementSingle Row Update

UPDATE PARTS SET COLOR =‘YELLOW’

WEIGHT = WEIGHT + 5CITY = NULL

WHERE P# = ‘P2’

Multiple row Update

UPDATE SUPPLIERSET STATUS = 2 * STATUS WHERE CITY = ‘MADRAS’

Page 133: DB2-1

DML – UPDATE StatementUpdate with a subquery UPDATE SHIPMENTSET QTY = 0 WHERE ‘LONDON = (SELECT CITY FROM SUPPLIER WHERE SUPPLIER.S # = SHIPMENT.S#)

Page 134: DB2-1

DML – UPDATE StatementUpdate with Referential IntegrityUPDATE SHIPMENTS SET S# =‘S20’ WHERE … SUPPLIERS.S# should have an entry S20

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

Page 135: DB2-1

DML – DELETE Statement

Syntax:

DELETE FROM table [WHERE condition]

Single row delete

DELETE FROM SUPPLIER WHERE S# = ‘S5’

Page 136: DB2-1

DML – DELETE StatementMultiple row delete DELETE FROM SHIPMENT WHERE QTY > 300

Delete with a subqueryDELETE FROM SHIPMENT WHERE ‘MADRAS’ = (SELECT CITY FROM SUPPLIER WHERE SUPPLIER.S# = SHIPMENT.S#)

Page 137: DB2-1

DML – DELETE StatementDelete with Referential Integrity

DELETE FROM SUPPLIERSWHERE S# = ‘S1’

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