MDI Training DB2 Course
-
Upload
marcus-davage -
Category
Documents
-
view
325 -
download
1
Transcript of MDI Training DB2 Course
DB2 for OS/390 Fundamentals
• Introduction to DB2• The Sample Database• Advanced SQL• Embedded SQL• Performance Topics• Tools of the trade
DB
2 fo
r OS/3
90
Fu
ndam
enta
ls
Introduction to DB2Universal Database
Intro
du
ction
to D
B2
• History• Workings
– Address spaces– Threads– Attachment Facilities
• SQL• DB2 Authorities• DB2 Objects• Referential Integrity• Commands and Utilities
1983 DB2 v1 ships1993 DB2 for OS/2 and Aix1994 DB2 for MVS v4 introduces Data
Sharing1996 DB2 UDB - multimedia, web-ready,
cross-platform (non-mainframe)1999 DB2 UDB for OS/390 (v6.1)2001 DB2 UDB for OS/390 and z/OS
(v7.1)2004 DB2 UDB for z/OS (v8.1)2004 DB2 UDB for LUW (v8.2)
A b
rief D
B2
Histo
ry
Directory
Catalog
Tables
Logs BSDS
DB2User
Thread
EDM Pool
Sort Pool
Buffer Pools
RID Pool
TemporaryDatabase
WorkingStorage
Program Logic
Th
e G
uts o
f DB
2
DBAS SSAS IRLM DDF SPAS
_DBM1 _MSTR _IRLM _DDF _SPAS
DatabaseFunctions
Logging Locking DistributedRequests
StoredProcedures
Buffering AttachmentCoordination
AddressSpace
Name
Functions
DBAS Database Services Address SpaceSSAS System Services Address SpaceIRLM Intersystem Resource Lock ManagerDDF Distributed Data FacilitySPAS Stored Procedure Address Space(s)
Th
e G
uts o
f DB
2
DB2
CICSPrograms
DB2 Utilities
TSOOnline
Programs
TSOBatch
Programs
QMF/DB2I(SPUFI)
threadthreads
thread
thread
thread
Th
read
s
DistributedPrograms
thread
DB2
TSO Address Space
DSN Processor
ISPF
DB2I
SPUFI
QMF
Rexx
Atta
chm
en
t Fa
cilities
Data
Sh
arin
g
• Shared data between subsystems
• Increased availability to data
• Expanded capacity
• Increased flexibility
• Easier upgrade path
• Parallelism exploited
Para
llelism
• Partitioned Tablespaces– DEGREE(ANY)
• BIND parameter
– SET CURRENT DEGREE = ‘ANY’;• SQL statement
• Types of Parallelism– I/O
• multiple read engines
– CP• multiple processor and read engines
– Sysplex• multiple data sharing subsystems
SQL
DCL
DDL
DML
GRANTREVOKE
CREATEALTERDROP
SELECTUPDATEINSERTDELETE
SQ
L
DB2
Request sent todatabase
Multiple rowsreturned asa results set
Resu
lts Sets
Au
thoritie
s
SYSADM Systems Administrator
Can do anything to everything
DBADM Database Administrator
Can do anything to a database
User-based Select, Update, Insert, Delete access on
permissions tables; Execute, Bind access on packages;
utilities/operations upon objects.
SYSMAINT/SYSCTRL Other administrative
DBMAINT/DBCTRL functions in DB2}{
STOGROUP
DATABASE
TABLESPACE
TABLE
VIEW
INDEXALIAS
SYNONYM COLUMN
DB
2 O
bje
cts
Menu Options View Utilities Compilers Help ----------------------------------------------------------------------------- DSLIST - Data Sets Matching FIGDB2.DSNDBC.DFIGE0H.*ABORT* Row 1 of 6 Command ===> Scroll ===> CSR Command - Enter "/" to select action Tracks %Used XT Device ----------------------------------------------------------------------------- FIGDB2.DSNDBC.DFIGE0H.SABORT.I0001.A001 FIGDB2.DSNDBD.DFIGE0H.SABORT.I0001.A001 1950 ? 31 3390
FIGDB2.DSNDBC.DFIGE0H.XABORT0.I0001.A001 FIGDB2.DSNDBD.DFIGE0H.XABORT0.I0001.A001 120 ? 6 3390
FIGDB2.DSNDBC.DFIGE0H.IABORT1.I0001.A001 FIGDB2.DSNDBD.DFIGE0H.IABORT1.I0001.A001 16 ? 15 3390 *************************** End of Data Set list ****************************
DB
2’s V
SA
M d
ata
se
ts
Partition number
Tablespace/Index name
Database name
High-level qualifier
Tab
lesp
ace
s
• Simple– only when you want to mix data from different tables on one page.
• Segmented– handles space more efficiently
– separates data from multiple tables in the same tablespace
• Partitioned– utilise parallelism
– very large amounts of data
– isolate data in dedicated page sets
• LOB (Large Object)– to store LOB data only
Tab
les
EMPNO FIRSTNME MIDINIT LASTNAME WORKDEPT PHONENO10 CHRISTINE I HAAS A00 397820 MICHAEL L THOMPSON B01 347630 SALLY A KWAN C01 473850 JOHN B GEYER E01 678960 IRVING F STERN D11 642370 EVA D PULASKI D21 783190 EILEEN W HENDERSON E11 5498
100 THEODORE Q SPENSER E21 972110 VINCENZO G LUCCHESI A00 3490120 SEAN O'CONNELL A00 2167
Rows
Columns
Colu
mn
s
• Requires a name– Cannot have duplicate names within a table
• Requires a data type
• Other attributes– NULLS ALLOWED/NOT NULL– DEFAULT VALUE– PRIMARY KEY– CHECK CONSTRAINT
SMALLINT/INTEGERCHARACTER/VARCHAR
GRAPHIC/VARGRAPHIC/DBCLOBCHARACTER LARGE OBJECT/CLOB
BINARY LARGE OBJECT/BLOBDECIMAL/NUMERIC
FLOAT/REAL/DOUBLEDATETIME
TIMESTAMPROWID
Data
typ
es
The user-defined DISTINCT TYPE is based on one of the previous basic data types.
E.g.
CREATE DISTINCT TYPE AUDIO AS BLOB (1M);CREATE DISTINCT TYPE VIDEO AS BLOB (1M);
Then, your CREATE TABLE statement might look like this:
CREATE TABLE VIDEO_CATALOG (VIDEO_NUMBER CHAR(6) NOT NULL, VIDEO_SOUND AUDIO, VIDEO_PICS VIDEO, ROW_ID ROWID NOT NULL GENERATED ALWAYS);
Use
r-Defin
ed
Data
ty
pes
Fun
ction
s
• Column Functions
• Scalar Functions
• User-defined Functions
Rou
tines
User-defined Functions
• Sourced
• External
Stored Procedures
• See next foil...
Sto
red
Pro
ced
ure
s
CallingProgram
MVS
Schedule SP
SELECT
INSERT
UPDATE
DELETE
DB2
Start ProcSELECT
INSERT
UPDATE
DELETEEnd Proc
SPAS
Call
Results
Oth
er fe
atu
res
• Relational Integrity– Joining tables relationally
• Triggers– firing actions to other tables (or calling stored
procedures which can call other programs) when tables are modified
• Constraints– build data rules into the database
• Labels
Ch
eck C
on
strain
ts
Data value restrictions on the contents of a column.
EXTN CHAR(4) CONSTRAINT NUMBER CHECK (EXTN BETWEEN ‘0000’ AND ‘9999’)
CONSTRAINT BYPASSCHECK(BYPASS IN ('Y', 'N')
AND (BYPASS = 'N' OR (BYPASS = 'Y’ AND REASON IS NOT NULL)))
Trig
gers
CREATE TRIGGER UPD_SALARYBEFORE UPDATE OF SALARY ON EMP FOR EACH ROW MODE DB2SQLWHEN (NEW.SALARY>(OLD.SALARY*1.5))BEGIN ATOMIC
SIGNAL SQLSTATE ‘75001’ (‘Raise exceeds 50%’);END;
CREATE TRIGGER RISK.GRT_DELAFTER DELETE ON RISK.GENERIC FOR EACH ROW MODE DB2SQLBEGIN ATOMIC
INSERT INTO RISK.AUDIT_TRAIL(TABLE_NAME, ACTION, GRT, GRTNAME, GRTDESC)VALUES('GENERIC','D', OLD.GRT, OLD.GRTNAME, OLD.GRTDESC);
END;
Rela
tion
al T
heory
• Nth normal form
• Primary Keys
• Unique Indexes
• Foreign Keys
Refe
ren
tial In
teg
rity
EMPEMPNOFIRSTNAMEMIDINITLASTNAMEWORKDEPTPHONENOHIREDATEJOBSEXBIRTHDATESALARYBONUS
DEPTDEPTNODEPTNAMEMGRNOADMRDEPTLOCATION
Ind
exes
• A structure that orders the values of columns in a table
• Administers Uniqueness
• Keeps data within the table in order
• Improves performance of SELECTS, UPDATES and DELETES
• Too many can degrade performance of INSERTS, some UPDATES and some DELETES
Ind
exes
DEPTNO DEPTNAME MGRNO ADMRA00 SPIFFI CO 10 -B01 PLANNING 20 A00C01 INFO 30 A00D01 DEVEL - A00
INDEXSPACE
TABLESPACE
TABLE DEPT
INDEX onDEPTNO
A00
B01
C01
D01
DB
2 C
om
man
ds a
nd
U
tilities
• Data Consistency Utilities
• Backup and Recovery Utilities
• Data Organisation Utilities
• Catalog Manipulation Utilities
• Offline Utilities
• Sample Programs
• DB2 Environment Commands
• DSN Commands
Som
e D
B2
Utilitie
s
• LOAD
• COPY
• REBUILD
• REORG
• RUNSTATS
• CHECK DATA
• REPAIR
• DIAGNOSE
• MERGECOPY
• MODIFY
• QUIESCE
• RECOVER
• REPORT
• STOSPACE
Som
e D
B2
C
om
man
ds
• DISPLAY– DATABASE (db) {SPACENAM(space)}
– BUFFERPOOL {ACTIVE | (*) | (bpname)}
– THREAD
– UTILITY
• START– DATABASE (db) {SPACENAM(space)}
• STOP– DATABASE (db) {SPACENAM(space)}
• TERM– UTILITY (util)
• CANCEL– THREAD (token)
• ALTER– BUFFERPOOL(bpname)
TS
O D
B2
C
om
man
ds
• DSN – {SYSTEM(subsystem)}
• BIND– PLAN
– PACKAGE
• DCLGEN
• FREE– PLAN
– PACKAGE
• REBIND– PLAN
– PACKAGE
• RUN– PROGRAM (progname) PLAN(planname)
• END
Sample Database
Sam
ple
Data
base
DEPT
EMP
PROJ
EMPPROJACTEMP_PHOTO_RESUME
ACT
PROJACT
1
2 3 4
5
6
7 8
91011
Sam
ple
Data
base
ACTNO ACTKWD ACTDESC
ACTDEPTDEPTNO DEPTNAMEMGRNO ADMRDEPTLOCATION
EMPEMPNO FIRSTNME MIDINIT LASTNAME WORKDEPT PHONENO HIREDATE
JOB EDLEVEL SEX BIRTHDATESALARY BONUS COMM
EMP_PHOTO_RESUME
EMPNO EMP_ROWID PSEG_PHOTOBMP_PHOTO RESUME EMPPROJACT
EMPNO PROJNO ACTNO EMPTIME EMSTDATEEMENDATE
PROJACTPROJNO ACTNO ACSTAFF ACSTDATEACENDATE
PROJPROJNO PROJNAMEDEPTNO RESPEMP PRSTAFF PRSTDATEPRENDATEMAJPROJ
Sam
ple
Data
base
• Create SQL Data Set
• Copy DDL members
• Ponder your DDL
• Execute it
• Play with it
• Now wash your hands
Sam
ple
Data
base
• Database• Tablespace
– Simple
– Segmented
– Partitioned
– LOB
• Tables– Bog standard
– Auxiliary
• Aliases• Synonyms
• Indexes– Unique
– Clustering
– Partitioning
• Views– Simple
– Complex
• RI– Primary Keys
– Foreign Keys
Sam
ple
Data
base
TablesACT
DEPT
EMP
EMP_PHOTO_RESUME
EMPPROJACT
PROJ
PROJACT
AUX_BMP_PHOTO
AUX_EMP_RESUME
AUX_PSEG_PHOTO
ViewsVACT VASTRDE1
VASTRDE2 VDEPMG1
VDEPT VEMP
VEMPDPT1 VEMPLP
VEMPPROJACT
VFORPLA VHDEPT
VPHONE VPROJ
VPROJACT
VPROJRE1
VPSTRDE1 VPSTRDE2
VSTAFAC1 VSTAFAC2
Th
e Jo
y o
f SQ
L
• Simple
• English
• Intuitive
• Flexible
• Complex
• Powerful
• You specify what, but don’t care how (DB2 takes care of that!)
Th
e Jo
y o
f SELE
CTs
SELECT { ALL | DISTINCT }[ * | [ [ expression | function | constant | column | host-variable | special-register | case-expression { {AS} column } ] |
table.* | view.* | correlation.*], ]FROM
[table | view | correlation | subselect [{INNER | LEFT OUTER | FULL OUTER } JOIN joined-table
ON join-condition]WHERE
[predicate | {NOT} = | < | > | <= | => | EXISTS | IN (in-list | subselect) |LIKE { ‘value%’ | ‘%value%’ | ‘%value’ }
value | subselect]GROUP BY [columns,]HAVING [predicate operator {value | subselect} ]
Exercise
• Using simple SQL…1. What is the full name and birthday of
employee ‘000030’?2. Which people have a salary of between
$30,000 and $50,000?3. Which people work in department ‘B01’ or
department numbers beginning with ‘C’?4. What department is ‘E21’?
Advanced SQL
Ad
van
ced
SQ
L
• Built-in Functions• Joins• Unions• Subqueries and Nested Table
Expressions• Sorting• Aggregation• CASE expressions• Date / Time Arithmetic• Global Temporary Tables• Existence
Colu
mn
Fun
ction
s
• Only in SELECT statements
• Operates upon a group of rows
• Apply to a named column or expression
• Returns a single value for the set of selected rows
• Returned value is of the same data type
• If clause finds no data, a null is returned, not SQLCODE+100
• Can be used to aggregate data with the GROUP BY clause
Sca
lar Fu
nctio
ns
• Apply to a column or expression
• Operate on a single value (not a set of data)
• May transform data type of original column
• Over 80 functions available
• User defined functions can be defined
Sp
ecia
l Reg
isters
• Date/Time– CURRENT DATE– CURRENT TIME– CURRENT TIMESTAMP
• Environment– CURRENT DEGREE– CURRENT SQLID– CURRENT SERVER– CURRENT PACKAGESET– USER– …and a few more uninteresting ones…
Join
s
Combining data from multiple tables based on the values of one or more columns in each table
• Cartesian Product– no matching columns specified
• Inner Join– where all columns match
• Left Outer Join– all matching rows
– all unmatching rows from Left table
• Full Outer Join– all matching rows
– all unmatching rows
Inn
er Jo
in
EMPNO LASTNAME WORKDEPT60 STERN D1170 PULASKI D21
150 ADAMSON D11160 PIANKA D11170 YOSHIMURA D11180 SCOUTTEN D11190 WALKER D11200 BROWN D11210 JONES D11220 LUTZ D11230 JEFFERSON D21240 MARINO D21250 SMITH D21260 JOHNSON D21270 PEREZ D21
200170 YAMAMOTO D11200220 JOHN D11200240 MONTEVERDE D21
SELECT EMPNO,LASTNAME, WORKDEPTFROM EMPWHERE WORKDEPT LIKE ‘D%';
SELECT DEPTNO,DEPTNAMEFROM DEPTWHERE DEPTNO LIKE 'D%'
DEPTNO DEPTNAMED01 DEVELOPMENT CENTERD11 MANUFACTURING SYSTEMSD21 ADMINISTRATION SYSTEMS
Inn
er Jo
in
EMPNO LASTNAME DEPTNAME60 STERN MANUFACTURING SYSTEMS
150 ADAMSON MANUFACTURING SYSTEMS160 PIANKA MANUFACTURING SYSTEMS170 YOSHIMURA MANUFACTURING SYSTEMS180 SCOUTTEN MANUFACTURING SYSTEMS190 WALKER MANUFACTURING SYSTEMS200 BROWN MANUFACTURING SYSTEMS210 JONES MANUFACTURING SYSTEMS220 LUTZ MANUFACTURING SYSTEMS
200170 YAMAMOTO MANUFACTURING SYSTEMS200220 JOHN MANUFACTURING SYSTEMS
70 PULASKI ADMINISTRATION SYSTEMS230 JEFFERSON ADMINISTRATION SYSTEMS240 MARINO ADMINISTRATION SYSTEMS250 SMITH ADMINISTRATION SYSTEMS260 JOHNSON ADMINISTRATION SYSTEMS270 PEREZ ADMINISTRATION SYSTEMS
200240 MONTEVERDE ADMINISTRATION SYSTEMS
SELECT EMPNO, LASTNAME, WORKDEPT DEPTNAMEFROM EMPJOIN DEPTON WORKDEPT = DEPTNOWHERE DEPTNO LIKE 'D%' ;
Ou
ter Jo
in
EMPNO LASTNAME DEPTNAME------ --------------- DEVELOPMENT CENTER
60 STERN MANUFACTURING SYSTEMS150 ADAMSON MANUFACTURING SYSTEMS160 PIANKA MANUFACTURING SYSTEMS170 YOSHIMURA MANUFACTURING SYSTEMS180 SCOUTTEN MANUFACTURING SYSTEMS190 WALKER MANUFACTURING SYSTEMS200 BROWN MANUFACTURING SYSTEMS210 JONES MANUFACTURING SYSTEMS220 LUTZ MANUFACTURING SYSTEMS
200170 YAMAMOTO MANUFACTURING SYSTEMS200220 JOHN MANUFACTURING SYSTEMS
70 PULASKI ADMINISTRATION SYSTEMS230 JEFFERSON ADMINISTRATION SYSTEMS240 MARINO ADMINISTRATION SYSTEMS250 SMITH ADMINISTRATION SYSTEMS260 JOHNSON ADMINISTRATION SYSTEMS270 PEREZ ADMINISTRATION SYSTEMS
200240 MONTEVERDE ADMINISTRATION SYSTEMS
SELECT EMPNO, LASTNAME, WORKDEPT DEPTNAMEFROM EMPRIGHT OUTER JOIN DEPTON WORKDEPT = DEPTNOWHERE DEPTNO LIKE 'D%' ;
Un
ion
s
Combining data from multiple results sets composed of all the rows in both of the two original sets
• Must contain the same number of columns• In the same order• Of the same data type (or convertible)• Contains no duplicates
– But UNION ALL overcomes this
Su
bq
uerie
s
• Nested SELECT statements• IN (or NOT IN)• EXISTS (or NOT EXISTS)• Comparative, equality/inequality operators
(=, <>, <, <=, >, >+)
• Correlated subqueries• Non-correlated subqueries
Neste
d T
ab
le
Exp
ressio
ns
• Allows the FROM clause to access another SELECT statement
– Wherever you see a table name, it can be another SELECT statement
• Sometimes called inline views• Can be replaced by VIEWs, but are easier to
understand• Must be enclosed by parentheses• Must be given a correlation name• Reaches the parts other statements cannot reach
Sortin
g
• By use of the ORDER BY clause• ORDER BY column1 ASC, column2 DESC
– specify the columns explicitly
• ORDER BY 1, 2, 3– specify the columns as they appear in the SELECT
statement
• Can be avoided by using an index which already specifies the columns and their order
Ag
gre
gatio
n
• “Bunching up”• Using GROUP BY and HAVING clauses• GROUP BY
– collates resultant rows to apply functions that consolidate the data
– can apply statistical functions on a column
• HAVING– eliminates non-pertinent groups of data from the
aggregated results set
Rela
tion
al D
ivisio
n
• Very useful, but very complex– The relational division of two tables is the operation of
returning rows whereby column values in one table match column values for every corresponding row in the other table
– A combination of correlated subqueries
– Example (SQL19) retrieves all projects that require every activity listing in the activity table• (No rows returned because no projects in the sample database
require all activities)
– Very powerful - SQL will out-perform any application-based solution using separate cursors to process three individual SELECT statements
• (I hardly ever use it!)
CA
SE E
xp
ressio
ns
• Uses the value of an expression to select one statement among many for execution
• Similar to programming language usage• Simplifies UNION coding• Improves performance• Very flexible• Can be used in SELECT clause and WHERE
clause
Date
an
d T
ime
Arith
metic
• Special data types– DATE
– TIME
– TIMESTAMP• One column instead of two
• Greater granularity
• Column functions to transform data types– YEAR, MONTH, DAY, HOUR, MINUTE, SECOND
• Arithmetic functions easy– But don’t mix dates with non-dates!
Glo
bal T
em
pora
ry
Tab
les
• Stores intermediate SQL results• Lasts as long as the process that uses it• CREATE GLOBAL TEMPORARY TABLE• Does not physically exist, but is instantiated when
first referenced• Locking, logging and recovery do not apply• No indexes - table scan access• No constraints or RI• No updates allowed, only SELECTs, INSERTs
and DELETEs• Great for Stored Procedures• Performance benefits
Existe
nce
• Not a David Cronenberg film• A much faster way of seeing if qualified data
exists than actually selecting it.– Less I/O to the data
• Not used often enough!• More than one way to skin a cat
– With an AK-47 sub-machine gun
– With a spoon
– With a blunt knife
– With a scalpel
Exercise
5. Rewrite member SQL13 to use an IN list instead of a UNION.
6. Who is Bruce Adamson’s boss?
7. Which employees have worked on project ‘OPERATION’?
8. How many people work for department ‘E21’ and what department is it?
9. Project ‘IF2000’ is allocated to which department?
10. What is the average salary for each department?
11. Which employee is paid the most?
12. Which employee is paid the least?
13. Who is the oldest employee?
14. Which projects are over/under budget, and by how much?
15. How many people work for each department?
Embedded SQL
Em
bed
ded
SQ
L
• Static– More efficient– Takes longer to code– Access path evaluation at Bind time– Hard coded
• Dynamic– More flexible– Can be modified during program execution– Requires PREPARE statements evaluated at
execution time– Access path evaluation at Execution time
DB2Catalog
DB2Directory
Sta
tic Pro
gra
m
Pre
para
tion
SourceProgram
DCLGEN
Precompiler
Modified SourceDBRM
Bind Compile
Link editPackage
Plan Load Module
Colle
ction
s in H
UO
N
SourceProgram
DBRM
LoadModule
BindPackage inFIGE1collection
FIGE1tables
Package inFIGE2collection
FIGE2tables
Package inFIGE3collection
FIGE3tables
Bind
Bind
Host v
aria
ble
s
• Output areas in the INTO clause of SELECTs and FETCHes
• Input areas for the SET clause of UPDATEs
• Input areas for the VALUES clause if INSERTs
• Search fields in the WHERE clause
• Literals in the SELECT list of a SELECT statement
• Include indicator variables for possible null values
Pro
gra
mm
ing
with
cu
rsors
• Rows vs. Results sets
• Syntax rules– Retrieval– Modification
• When to use cursors (and when not to)
• Gotchas– SQLCODE -811– Table materialisation (OPEN or FETCH)– Specify required columns
Pro
gra
mm
ing
with
cu
rsors
DECLARE C1 CURSOR FOR
SELECT DEPTNO, DEPTNAME
FROM DEPT
WHERE ADMRDEPT = :ADMRDEPT
Pro
gra
mm
ing
with
cu
rsors
Results Set
OPEN C1
Pro
gra
mm
ing
with
cu
rsors
Results SetFirst fetch...
FETCH C1 INTO
:DEPTNO, :DEPTNAME
Pro
gra
mm
ing
with
cu
rsors
Results SetNext one…
FETCH C1 INTO
:DEPTNO, :DEPTNAME
Pro
gra
mm
ing
with
cu
rsors
Results SetAnd again…
FETCH C1 INTO
:DEPTNO, :DEPTNAME
Pro
gra
mm
ing
with
cu
rsors
Results SetAnd again…
FETCH C1 INTO
:DEPTNO, :DEPTNAME
Pro
gra
mm
ing
with
cu
rsors
Results Set...
…and so on until the last line of the results set…
…the next FETCH returns an SQLCODE of +100, with no rows returned.
Host variables may or may not contain valid data at this point, so ALWAYS check your SQLCODE before processing your data!
Pro
gra
mm
ing
with
cu
rsors
Always clean up your cursors!
Data processing is finalised, the cursor is closed and all your results set storage is cleared up once you issue the
CLOSE C1
statement, after your FETCH processing gets the +100 SQLCODE signifying the end of the results set.
Pro
gra
mm
ing
with
cu
rsors
• Rows vs. Results sets
• Syntax rules– Retrieval– Modification
• When to use cursors (and when not to)
• Gotchas– SQLCODE -811– Table materialisation (OPEN or FETCH)– Specify required columns
Pro
gra
mm
ing
with
cu
rsors
• Rows vs. Results sets
• Syntax rules– Retrieval– Modification
• When to use cursors (and when not to)
• Gotchas– SQLCODE -811– Table materialisation (OPEN or FETCH)– Specify required columns
• WITH HOLD
• Explicitly declare all DB2 tables– DCLGEN
• SQLCA
• SQLDA
• Error handling– Check SQLCODE and SQLSTATE every time!– Use standard error routine if available
More
Pro
gra
mm
ing
Tip
s
Performance:The Black Arts
Perfo
rman
ce
• Commitment control– COMMIT– ROLLBACK
• Locking
• Concurrency
• Isolation Levels– BIND parameters (package level)– the WITH clause (statement level)
• SQL– use indexes– careful predicates
Perfo
rman
ce
• Best Coding Practice– Online environments
• plan for multiple user concurrency
– Batch environments• frequent commits
• restartability
• Tools– DB2 Traces, MainView, Strobe
• EXPLAIN– PLAN_TABLE
Com
mitm
en
t
• UNIT OF WORK
• COMMIT– EXEC CICS SYNCPOINT– Externalises updated data since Unit of Work
began– Releases locks
• ROLLBACK– EXEC CICS ROLLBACK– Undoes updated data since Unit of Work began– Releases locks– Automatic rollback on error/failure
Un
it of W
ork
time
Programbegins
Update Insert Delete COMMIT
Log
Un
it of W
ork
time
Programbegins
Update Insert Delete
ROLLBACK
Lockin
g
• Ensures data integrity
• Prevents multiple conflicting updates
• Level of Locking– Table, Tablespace– Page– Row
• Locks released on COMMIT or ROLLBACK
• Locks consume resources
• Lock escalation
• LOCK TABLE command
Con
curre
ncy
Lock MeaningAccess Required
Access Allowed How got
S SHARE Read only Read onlySelect/Open/Fetch
U UPDATE
Read with intent to update Read only
Select/Fetch for update of
X EXCLUSIVE Update No accessUpdate/Insert/Delete
Page Lock Matrix
Isola
tion
Levels
• Repeatable Read (RR)– I’m reading it. You can’t have it. Bog off.
• Read Stability (RS)– I’m reading it, but you can add more pages at
the end.
• Cursor Stability (CS)– I’m reading it, but you can update what I’ve
read once I’ve turned the page.
• Uncommitted (dirty) Read (UR)– I’m reading it, but you can change it while I’m
reading it, and I don’t care if you back it out before I’ve finished.
Exam
ple
• Locking
• Commit/Rollback
• Concurrency
• Isolation Levels
SQ
L Perfo
rman
ce
• The No. 1 biggest performance headache
• Why?– Badly coded SQL
• Is your SQL the best method of getting your data?
• Is there an alternative way of coding your SQL?
– Badly designed or missing predicates• Especially high-order columns
– Available indexes not used• Check first
– Badly designed database• Indexes incorrectly specified
• The No. 1 easiest and quickest win
Best C
od
ing
Pra
ctice
• Online environments– plan for multiple user concurrency– keep UPDATES, INSERTS and DELETES to a
minimum, and close together, if possible– COMMIT a.s.a.p. afterwards
• Batch environments– frequent commits (every 1000 updates or so)– plan for restartability
• Use UR with caution– can bring massive benefits– can bring disastrous results
Perfo
rman
ce T
ools
• DB2 Traces– Performance
– Audit
– Statistics
• DB2 Explain
• BMC– AppTune
– MainView• CICS
• DB2
• z/OS
• Strobe– DB2 activity
– CICS activity
– COBOL statements
• RMF– system delays
– disk/data set contention
• CANDLE– Workbench
EX
PLA
IN
Explain
Plan, Package or SQL statement
DB2Optimizer
PLAN_TABLE
DSN_STATEMENT_TABLE
DSN_FUNCTION_TABLE
EXPLAIN ALL SET QUERY=1 FORSELECT FIRSTNME, MIDINIT,
LASTNAMEFROM EMPWHERE EMPNO=‘000240’;
Tools of the trade
Tools
• Data Entry and Modification– SPUFI
– File Aid for DB2
– CA Pro-Edit
– BMC Catalog Manager
• Catalog Navigation– SPUFI
– BMC Catalog Manager
• Query Reporting– SPUFI
– QMF
• Performance– Candle Explain
Tools
• File Aid for DB2– Browsing and Editing tables
– Loading and Unloading tables
• BMC Catalog Manager– Browsing and Editing tables
– DB2 object dependencies
– Catalog Navigation
– JCL and Utility generation
• SPUFI– Data modification
– Reporting
– Catalog Navigation
• Candle Explain
• Introduction to DB2• The Sample Database• Advanced SQL• Embedded SQL• Performance Topics• Tools of the trade
DB
2 fo
r OS/3
90
Fu
ndam
enta
ls
• Further help is available from:– Manuals– Books
• The DB2 Developer’s Guide• DB2 Answers
– The Internet• http://www.ibm.com/software/data/db2/
– More courses(!)– Your friendly DBA
DB
2 fo
r OS/3
90
Fu
ndam
enta
ls