Top Banner
1 DB2 for z/OS Technical Conference Sept 05-07, 2007 - Shanghai, China Sept 10-12, 2007 - Beijing, China DB2 for z/OS V8, V9 New SQL Features Steve Chen [email protected]
62

Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

Jan 20, 2015

Download

Documents

Tess98

 
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

1

DB2 for z/OS Technical Conference Sept 05-07, 2007 - Shanghai, ChinaSept 10-12, 2007 - Beijing, China

DB2 for z/OS V8, V9 New SQL Features

Steve Chen [email protected]

Page 2: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

2

DB2 for z/OS Technical Forum

Table of Content

New SQL Features in V8

New SQL Features in V9

Page 3: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

3

DB2 for z/OS Technical Forum

New SQL Functions in V8Breaking the Limit -- Long ObjectsMulti-row FETCH & INSERTINSERT within SELECT StatementIdentity Column ImprovementSequencesDynamic Scrollable CursorsCommon Table Expressions & Recursive SQLStage 1 predicates for unlike-data typesMaterialized Query TablesMultiple DISTINCTMultiple CCSID per StatementScalar Full Select

Page 4: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

4

DB2 for z/OS Technical Forum

Key New SQL Functions in V8 - Cont'd

REOPT(ONCE)Explain Statement CacheTransparent ROWID columnSession VariablesVOLATILE Table SupportTable UDF Enhancement

Page 5: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

5

DB2 for z/OS Technical Forum

Virtual Storage 2 GB 2**31 to 2 **64Table name sizes 18 to 128Column name sizes 18 to 30Partitions 254 to 4096SQL statement length 32K to 2 MBIndex key size 255 to 2000Literals 255 to 32704Short strings 255 to 32704Predicates 255 to 32704

Breaking the limits

Page 6: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

6

DB2 for z/OS Technical Forum

Tables in a join 15 to 255Current optimization hint 8 to 128CURRENT PACKAGESET 18 to 128CURRENT PATH 254 to 2048CURRENT SQLID 8 to 128USER 8 to 128VIEW Name 18 to 128ALIAS Name 18 to 128......

Breaking the limits ....

Page 7: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

7

DB2 for z/OS Technical Forum

INSERT INTO T1 VALUES( :ARRAY1, :ARRAY2) FOR :hv ROWS NOT ATOMIC CONTINUE ON SQLEXCEPTION;

Multi-row INSERTInserts multiple rows on one API callCan be ATOMIC or NOT ATOMICCan be static or dynamic SQLSignificant performance boost

Page 8: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

8

DB2 for z/OS Technical Forum

Multi-row FETCH

Returns multiple rows on one API crossing"wide" cursor with locks on multiple rowsSupports scrollable and non-scrollable, static and dynamic SQLSignificant performance boost

DECLARE C1 CURSOR WITH ROWSET POSITIONING FOR SELECT COL1, COL2 FROM T1;

OPEN C1;

FETCH NEXT ROWSET FROM C1 FOR :hv ROWS INTO :ARRAY1, :ARRAY2;

Page 9: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

9

DB2 for z/OS Technical Forum

Positioned UPDATE/DELETE of Multi-row FETCH

Allows positioned UPDATE or DELETE to be used on a "wide" cursorUpdate all rows Or update a specific row

UPDATE T1 SET COL1='ABC' WHERE CURRENT OF CURSOR C1 FOR ROW :hv OF ROWSET

Page 10: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

10

DB2 for z/OS Technical Forum

INSERT within SELECT

Elegant technique for retrieving values created / modified by DB2 during INSERT

identity columns, sequence valuesuser-defined defaults, expressionscolumns modified by triggersROWIDs, CURRENT TIMESTAMP, �

SELECT C1, C2, C3, C4, C5 FROM FINAL TABLE (INSERT (C1, C5) INTO T1 VALUES('ABC', CURRENT DATE));

Page 11: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

11

DB2 for z/OS Technical Forum

ALTER support for Identity ColumnsGENERATED ALWAYS | BY DEFAULTRESTART WITH valueINCREMENT BYMINVALUE | NO MINVALUEMAXVALUE | NO MAXVALUECYCLE | NO CYCLECACHE | NO CACHEORDER | NO ORDER

Identity Column Improvements

Page 12: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

12

DB2 for z/OS Technical Forum

Sequences

CREATE SEQUENCEALTER SEQUENCERESTART WITH valueINCREMENT BYMINVALUE, MAXVALUECYCLE/NO CYCLECACHE/NO CACHEGRANT/REVOKE privileges for sequence objectNEXT VALUE FOR expressionPREVIOUS VALUE FOR expression

Page 13: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

13

DB2 for z/OS Technical Forum

Dynamic Scrollable Cursors

Scrollable cursor provides access to base table rather than work file -- allows viewing of updates by others. Defaults to single row fetch, so DDF applications should use:multi-row FETCHpositioned update/delete for multi-row FETCH

DECLARE C1 SENSITIVE DYNAMIC SCROLL CURSOR FOR SELECT C1, C2 FROM T1;

Page 14: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

14

DB2 for z/OS Technical Forum

Common Table Expressions (CTE) & Recursion

Refer to table-name later in SQLAllow in SELECT, CREATE VIEW, INSERTWITH table-name [ column-list ] AS fullselectFor recursion fullselect of CTE refers to itself

fullselect that does not refer to CTE UNION ALL fullselect that refers to CTE

Page 15: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

15

DB2 for z/OS Technical Forum

WITH RPL (PART, SUBPART, QUANTITY) AS ( SELECT R.PART, R.SUBPART, R.QUANTITY FROM PARTLIST AS R WHERE R.PART = '01' UNION ALL SELECT C.PART, C.SUBPART, C.QUANTITY FROM RPL AS PARENT, PARTLIST AS C WHERE PARENT.SUBPART = C.PART ) SELECT DISTINCT PART, SUBPART, QUANTITY FROM RPL ORDER BY PART, SUBPART, QUANTITY;

Common Table Expression & Recursion Example

Page 16: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

16

DB2 for z/OS Technical Forum

Stage 1 Predicate for Unmatch Operands

Turning Predicate to stage-1 predicate aggressivelyEmploying stage-1 predicate in indexSignificant performance improvement for many applications

Emp (Name char(11), Gender char(1), Sal int)

SELECT * FROM EMPWHERE Gender ='F' AND Sal > 999999.99;

Evaluated as a Stage-2 predicateFetching half of the EMP table through the index on the Gender columnApply the stage-2 predicate

Evaluated as a Stage-1 predicateFetching 10% of the EMP table through

the index on the Sal columnApply the stage-1 predicate

prior to V8 V8 & beyond

Page 17: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

17

DB2 for z/OS Technical Forum

SELECT * FROM EMP E, DIVISION DWHERE E.Sal > D.Midmark * 1.25 AND E.Division = D.Id AND D.Midmark > 50000

Stage 1 Predicate for Unmatch Operands

Evaluated as a Stage-2 predicateJoin DIVISION to EMPFetch EMP records for the divisionApply the stage-2 predicate

Evaluated as a Stage-1 predicateJoin DIVISION to EMPFetch EMP records through the

index on E.Division or index on E.SalApply the stage-1 predicate

prior to V8 V8 & beyond

Page 18: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

18

DB2 for z/OS Technical Forum

Materialized Query Tables

Sometimes called Summary Tables, Automatic Summary Tables, Automatic Materialized Query Tables, Materialized Views, ...Optimizer can rewrite queries to access MQT instead of base table or viewPre-computed information, very significant performance improvementManaged by user or system (SQL REFRESH)Automatic rewrite or manualInformational Referential Integrity (not enforced)

Page 19: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

19

DB2 for z/OS Technical Forum

Click here to type page title

Page 20: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

20

DB2 for z/OS Technical Forum

Click here to type page title

Page 21: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

21

DB2 for z/OS Technical Forum

CREATE TABLE DATAMART_MQT AS (SELECT T.MONTH, P.KIND, SUM(F.QTY * F.PRICE) TOTALSUM(F.QTY * F.PRICE) CNTFROM Transacs F, Calendar T, Products P, Stores SWHERE F.DID = T.ID ANDF.PID = P.ID ANDF.SID = S.ID ANDGROUP BY P.KIND, T.MONTH, S.SALESZONE )DATA INITIALLY DEFERREDREFRESH DEFERREDMAINTAINED BY SYSTEMENABLE QUERY OPTIMIZATIONIN ...;

Materialized Query Table

Page 22: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

22

DB2 for z/OS Technical Forum

Materialized Query TableSELECT T.MONTH, P.KIND, AVG (F.QTY * F.PRICE) AVGAMTFROM Transacs F, Calendar T, Products P, Stores SW HERE F.DID = T.ID ANDF.PID = P.ID ANDF.SID = S.ID ANDT.MONTH IN ('01/01', '02/01', '01/02', '02/02') ANDP.KIND IN ('FOOD', 'DRINK', 'TOOLS')GROUP BY P.KIND, T.MONTHORDER BY T.MONTH, P.KIND;AFTER QUERY

SELECT MONTH, KIND,CASE WHEN SUM(CNT) = 0 THEN NULLELSE SUM(TOTVAL)/SUM(CNT) END AVGAMTFROM DATAMART_MQTWHERE MONTH IN ('01/01', '02/01', '01/02', '02/02') ANDKIND IN ('FOOD', 'DRINK', 'TOOLS')GROUP BY KIND, MONTHORDER BY MONTH, KIND;

Query Rewrite

Page 23: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

23

DB2 for z/OS Technical Forum

Multiple DISTINCTDistinct keyword can be specified more than once as long as the semantics is well-definedIn SELECT list and HAVING clause

select count(distinct(c1)), count(distinct(c2)) ...select avg(distinct(c1)), sum(distinct(c2)) ...select min(distinct(c1)), max(distinct(c2))

from t where c3 > 100 group by c4select count(distinct(c1)) from t group by c2

having avg(distinct(c3)) > 1

Page 24: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

24

DB2 for z/OS Technical Forum

Multiple CCSIDs per Statement

A single SQL statement can now intermix EBCDIC, ASCII and Unicode tables and host variablesUnlike host variables are translated to column CCSIDUnlike column CCSIDs are "promoted" to UnicodeMay require query to be materialized/sorted

SELECT e.C1 || a.C1 , e.C2 || GX'42C1' FROM ET e, AT a, UT u WHERE e.C1 = u.C1 and a.C2 = GX'42C1' and UX'42C142C2' = X'C1C2'

Unicode

ASCII

EBCDIC

Unicode Unicode

Page 25: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

25

DB2 for z/OS Technical Forum

Scalar fullselect

Allows scalar fullselect where expressions were previously supportedResult is the null value if the fullselect does not return a row.SQLCODE -811 if more than one row returned

select product, pricefrom productswhere price between 2 * (select min(price) from products) and 0.5 * (select max(price) from products);

select part, (select price from partprice where part = a.part) from parts a

Page 26: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

26

DB2 for z/OS Technical Forum

Scalar fullselect - 2

UPDATE NEW_PARTPRICE N SET PRICE = CASE WHEN( (SELECT ONHAND# FROM INVENTORY WHERE PART=N.PART) < 7 ) THEN 1.1 * PRICE WHEN( (SELECT ONHAND# FROM INVENTORY WHERE PART=N.PART) > 2 ) THEN .8 * PRICE ELSE PRICE END;

Page 27: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

27

DB2 for z/OS Technical Forum

IS NOT DISTINCT FROMA new predicate to support NULL = NULL

IS NOT DISTINCT FROM --- (similar to equal)IS DISTINCT FROM ---- (similar to not equal)

SELECT C1 FROM T1 WHERE C1 IS NOT DISTINCT FROM :hv;

C1 value :hv value resultNull 'abc' falseNull Null true'abc' 'abc' true'abc' Null false'abc' 'def' false

SELECT C1 FROM T1 WHERE C1 IS DISTINCT FROM :hv;

C1 value :hv value resultNull 'abc' trueNull Null false'abc' 'abc' false'abc' Null ture'abc' 'def' ture

Page 28: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

28

DB2 for z/OS Technical Forum

REOPT(ONCE) BIND Option

Controls when DB2 builds access path for dynamic SQL Default, access path is calculated at PREPARE.REOPT(ONCE)

Defers access path selection until OPENValues of host variables on OPEN used to calculate access path at the first executionResulting access path cached in the statement cache

Page 29: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

29

DB2 for z/OS Technical Forum

EXPLAIN for Global Statement Cache

Enhancements to the EXPLAIN statement allow you to obtain EXPLAIN information for entries in the DB2 global statement cacheVisual Explain uses this new function.

EXPLAIN STMTCACHE STMTID=integer STMTTOKEN=string

Page 30: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

30

DB2 for z/OS Technical Forum

Transparent ROWID column

Eliminates the need to explicitly declare a ROWID column in tables that include LOBs

DB2 will generate a "hidden" ROWID column, which is not visible on SELECT *

Simplifies porting of LOB applications from other platforms

Page 31: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

31

DB2 for z/OS Technical Forum

Session Variables

Variables set by DB2, connection or signon exitBuilt in function to retrieve value for a variableUse function in views, triggers, stored procedures & constraints to enforce security policyCan have more general, flexible access checks Multiple columns, AND/OR logic, ... PLAN, PACKAGE, SECLABEL, VERSION, ...Complements other security mechanisms

CREATE VIEW V1 AS SELECT * FROM T1 WHERE COL5 = GETVARIABLE(SYSIBM.SECLABEL);

Page 32: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

32

DB2 for z/OS Technical Forum

VOLATILE Table SupportEncourages index access for tables that have unpredictable cardinality Disable List Prefetch and certain optimizationSignificant performance improvement for some SAP applications

CREATE TABLE XYZ ...... VOLATILE

Page 33: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

33

DB2 for z/OS Technical Forum

Table UDF EnhancementTable UDF Cardinality clause

Specify the expected number of rows returned by UDFUsed by optimizer for better access path

TABLE UDF block fetchAll rows are returned during the first invocation of the UDFStore the returned rows into workfile

Predicate using TABLE UDF indexable and stage 1

Select * from books b, table(contains(1, 'database') CARDINALITY 15000) as X1(ID) where b.id = X1.id;

Stage 2 predicateR scan on books

Stage 2 predicate, if book --> TUDF Stage 1 predicate, if TUDF --> books

prior to V8 V8 and beyond

Page 34: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

34

DB2 for z/OS Technical Forum

DB2 Catalog V8

Longer names (128 byte varchar Unicode) table, view & aliascolumn (30)schema UDF, stored procedures, triggers, package

Some page sizes greater than 4K4K, 8K, 16K, 32K pages in DB2 catalog

Indexes longer than 255 bytes Contains Unicode data

Page 35: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

35

DB2 for z/OS Technical Forum

DB2 for z/OS Technical Forum

Click to edit Master title style

SQL Enhancements in V9

Page 36: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

36

DB2 for z/OS Technical Forum

Key SQL Functions in V9New data types: BIGINT, BINARY, VARBINARY, DECFLOATInstead of TriggerMergeSELECT FROM MERGE/UPDATE/DELETEORDER BY and FETCH FIRST in subselectTRUNCATEINTERSECT/EXCEPTIndex on ExpressionFETCH Continue

Page 37: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

37

DB2 for z/OS Technical Forum

Sparse Index and In Memory Data CachingDynamic Index Anding and Star SchemaOLAP specification -- RANK, DENSE_RANK, ROW_NUMBERRENAME INDEX/COLUMNREOPT (AUTO)Clone TableSpatial

Key SQL Functions in V9 - cont'd

Page 38: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

38

DB2 for z/OS Technical Forum

New data types: BIGINT, BINARY, VARBINARY, DECFLOAT

BIGINT - big integer.Big integer is a binary integer with a precision of 63 bits. The range of big integers is [-9223372036854775808, 9223372036854775807

BINARY ? fixed-length binary string. Fixed-length binary string is in a range of [1,255]. The padding with hexadecimal zeros (X? 0?. Not associated with any CCSID

VARBINARY ? varying-length binary string. Varying-length binary string is in a range of [1,32704]. No padding is performed. Not associated with any CCSID

DECFLOAT ? Decimal float. DECFLOAT(16) = decimal64 format (8 bytes)DECFLOAT(34) = decimal128 format (16 bytes)

Page 39: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

39

DB2 for z/OS Technical Forum

DECFLOAT

-1.000000000000000000000000000000000x10-6143Largest negative DECFLOAT(34) Value

1.000000000000000000000000000000000x10-6143Smallest positive DECFLOAT(34) Value

9.999999999999999999999999999999999x106144Largest DECFLOAT(34) Value

-9.999999999999999999999999999999999x106144Smallest DECFLOAT(34) Value

-1.000000000000000x10-383Largest negative DECFLOAT(16) value

1.000000000000000x10-383Smallest positive DECFLOAT(16) Value

9.999999999999999x10384Largest DECFLOAT(16) Value

-9.999999999999999x10384384Smallest DECFLOAT(16) Values

LimitDescription

-1.000000000000000000000000000000000x10-6143Largest negative DECFLOAT(34) Value

1.000000000000000000000000000000000x10-6143Smallest positive DECFLOAT(34) Value

9.999999999999999999999999999999999x106144Largest DECFLOAT(34) Value

-9.999999999999999999999999999999999x106144Smallest DECFLOAT(34) Value

-1.000000000000000x10-383Largest negative DECFLOAT(16) value

1.000000000000000x10-383Smallest positive DECFLOAT(16) Value

9.999999999999999x10384Largest DECFLOAT(16) Value

-9.999999999999999x10384384Smallest DECFLOAT(16) Values

LimitDescription

Both IEEE and hexadecimal floating point numbers can only approximate common decimal numbers. But DFP can represent decimal number exactly.

DFP can represent much bigger and smaller number than DECIMAL.

Page 40: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

40

DB2 for z/OS Technical Forum

Instead of TriggerA new type of trigger (~ BEFORE, AFTER triggers)Defined on VIEWs

provides an extension to the updatability of viewsrequested update operation against the view gets replaced by the trigger logicapplication still believes all operations are performed against the viewapplicable even for updatable views

Page 41: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

41

DB2 for z/OS Technical Forum

Instead of TriggerCREATE TABLE WEATHER (CITY VARCHAR(25), TEMPF DECIMAL(5,2));CREATE VIEW CELCIUS_WEATHER_V (CITY, TEMPC) AS SELECT CITY, (TEMPF-32)*5.00/9.00 FROM WEATHER

CREATE TRIGGER CW_INSERT INSTEAD OF INSERT ON CELCIUS_WEATHER_VREFERENCING NEW AS NEWCW DEFAULTS NULLFOR EACH ROW MODE DB2SQL INSERT INTO WEATHER VALUES (NEWCW.CITY, 9.00/5.00*NEWCW.TEMPC+32)

CREATE TRIGGER CW_UPDATE INSTEAD OF UPDATE ON CELCIUS_WEATHER_VREFERENCING NEW AS NEWCW OLD AS OLDCW DEFAULTS NULLFOR EACH ROW MODE DB2SQL UPDATE WEATHER AS W SET W.CITY = NEWCW.CITY, W.TEMPF = 9.00/5.00*NEWCW.TEMPC+32 WHERE W.CITY = OLDCW.CITY

Page 42: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

42

DB2 for z/OS Technical Forum

MergeCombine Update and Insert operation to a target table or view, from a input source of a list of host-variable-arrays modeled as a source table

When source rows match to target, Update target rows from sourceWhen source rows do not match to target, Insert source rows into targetUpdate/Insert triggers will be fired

MERGE INTO account AS T USING VALUES (:hv_id, :hv_amt) FOR 5 ROWS AS S(id,amt)ON T.id = S.id WHEN MATCHED THEN UPDATE SET balance = T.balance + S.amt WHEN NOT MATCHED THEN INSERT (id, balance) VALUES (S.id, S.amt)NOT ATOMIC CONTINUE ON SQLEXCEPTION

Page 43: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

43

DB2 for z/OS Technical Forum

SELECT FROM MERGE/UPDATE/DELETEV8 - The INSERT statement was allowed in the FROM clause V9 - A searched UPDATE/DELETE is now allowed in the FROM clause

SELECT SUM(Salary)FROM OLD TABLE(DELETE FROM Employee WHERE Level = 'Contractor');

Delete employees at level 'Contractor' and return the total amount of salary:

Page 44: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

44

DB2 for z/OS Technical Forum

SELECT FROM MERGE/UPDATE/DELETE

Update salaries of employees at level 'Associate' and return the new salary:

SELECT Name, SalaryFROM FINAL TABLE(UPDATE Employee SET Salary = Salary *1.1 WHERE Level = 'Associate');

Update salaries of employees at level 'Associate' and return the old salary:

SELECT Name, SalaryFROM OLD TABLE(UPDATE Employee SET Salary = Salary *1.1 WHERE Level = 'Associate');

Page 45: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

45

DB2 for z/OS Technical Forum

ORDER BY and FETCH FIRST in subselect

ORDER BY clause can be specified in subselect or fullselectFETCH FIRST n ROWS ONLY clause can be specified in subselect or fullselectORDER OF table-designator extension to the ORDER BY clause

(SELECT * FROM T1 ORDER BY C1)UNION(SELECT * FROM T2 ORDER BY C2 FETCH FIRST 2 ROWS)

(SELECT * FROM T1 ORDER BY C1)UNIONSELECT * FROM T2 ORDER BY C2FETCH FIRST 2 ROWS

Page 46: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

46

DB2 for z/OS Technical Forum

Using the EMP_ACT table, find the project numbers that have an employee whose salary is in the top 3 of all employees.

SELECT EMP_ACT.EMPNO, PROJNOFROM EMP_ACTWHERE EMP_ACT.EMPNO IN (SELECT EMPLOYEE.EMPNO FROM EMPLOYEE

ORDER BY SALARY DESC FETCH FIRST 3 ROWS ONLY )

EMPNO SALARY 5 100,000 8 50,000 11 60,000 12 150,000 18 30,000 22 80,000 23 55,000

EMPNO PROJNO 5 100 8 101 11 123 12 100 18 112 22 105 23 107

EMPNO SALARY 12 150,000 5 100,000 22 80,000

Employee EMP_ACT

ExampleExample

subq

Page 47: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

47

DB2 for z/OS Technical Forum

TRUNCATE TableA fast way to empty a tableDELETE Triggers are ignoredIndexes, LOB, XML Tablespaces are also deletedX lock on the target table, Mass-delete

TR U NCAT E < TAB LE> TAB LE-NAM E

< D R O P STO R AGE | R EU SE STO R AGE>

< R ESTR I CT W H EN D ELETE TR I GGER S | I GNO R E D ELET E T R I GGER S>

< I M M ED I ATE>

Page 48: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

48

DB2 for z/OS Technical Forum

INTERSECT/EXCEPT

SELECT c11, c12, ? c1n FROM T1 <set-op> SELECT c21, c22, ? c2m FROM T2

SET operator: UNION, INTERSECT, EXCEPT

I N T E R S E C T E X C E P T ( D i f f e r e n c e )

U N I O N

R 1 R 1R 2 R 2

R 1 R 2

I N T E R S E C T E X C E P T ( D i f f e r e n c e )

U N I O N

R 1 R 1R 2 R 2

R 1 R 2R 1 R 2

Page 49: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

49

DB2 for z/OS Technical Forum

INTERSECT/EXCEPT

5

4

4

4

3

3

3

35

34

24

243

5232

45132

424132

4323131

31522111

11211111

INTERSECTINTERSECT ALLEXCEPTEXCEPT

ALLUNIONUNION ALLR2R1

5

4

4

4

3

3

3

35

34

24

243

5232

45132

424132

4323131

31522111

11211111

INTERSECTINTERSECT ALLEXCEPTEXCEPT

ALLUNIONUNION ALLR2R1

Page 50: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

50

DB2 for z/OS Technical Forum

Index on ExpressionCreate index on result of ExpressionEnhance Query PerformanceIf we want to search for customers whose Upper(Lastname) = 慡MITH�

CREATE INDEX IX_LastName ON CUSTOMER ( UPPER (Lastname), CUSTOMER_ID);

SELECT * FROM EMP WHERE UPPER (Lastname) = 'SMITH';

R o o t

S M IT H S m i th b u s h s m it h

R o o t

S M IT H S m i th b u s h s m it h

Root

BUSHSMITH(Brian)SMITH(John)SMITH(Kyle)

… ZAJAC

Root

BUSHSMITH(Brian)SMITH(John)SMITH(Kyle)

… ZAJAC

Page 51: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

51

DB2 for z/OS Technical Forum

Index on Expression - 2CREATE INDEX IX1 ON T1 ( HEX(c1), BINARY(LTRIM(c2)) );CREATE INDEX IX2 ON T2 (SUBSTR(c2, 1, 23), CONCAT(c2, c3));CREATE INDEX IX3 ON T2 (salary, bonus/salary, bonus+salary);CREATE INDEX IX4 ON T1 (DAYOFYEAR(endship) - DAYOFYEAR(startship));CREATE INDEX IX5 ON T2 (GRAPHIC(c3));CREATE INDEX IX6 ON T1 (VARCHAR(INSERT(vchar30,1,0,''),20));CREATE INDEX IX7 ON T1 (posstr(lvcharx2, '7.2E+02')) ;CREATE INDEX IX8 ON T1 (MIDNIGHT_SECONDS(birthday));

Page 52: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

52

DB2 for z/OS Technical Forum

FETCH CONTINUEProvides 2 new syntax extensions on FETCH for LOB and XML data:

FETCH WITH CONTINUEJust like a regular FETCH but�Tells DB2 how to react when truncation occurs on output of a LOB or XML columnPreserve the rest of the data, remember positiionIn the output length field, return the size that the host variable should have beenNo effect on VARCHAR column truncation�

FETCH CURRENT CONTINUETells DB2 to continue fetching from the truncation pointThe CURRENT keyword implies 搒tay on the same row�Can be executed multiple times to 搒tream?the data揜 ow-based?operation ? DB2 tries retrieve all truncated LOB/XML columns. Column-based operation can be achieved by setting output lengths to zero for other columns

Page 53: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

53

DB2 for z/OS Technical Forum

FETCH CONTINUE – Basic Application Flow

Integer hostvar1

char[32767] hostvar2

Char[ ] *hostvar3 “based” structure

DECLARE CURSOR C1 FOR

SELECT INTCOL, CLOBCOL FROM T1 …

OPEN C1

FETCH WITH CONTINUE C1INTO :hostvar1, :hostvar2

If hostvar2 was truncated

{

get length from output length field

allocate storage to hold the rest

FETCH CURRENT CONTINUE INTO :hostvar3

}

Application DB2

I’m a loo…oong LOB74I’m a short LOB23

T1INTCOL CLOBCOL (10MB)

741048576 | I’m a looo…oooo

1015809 | ooooooo…ooooooong LOB

heap storage:

Assume 1MB

Page 54: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

54

DB2 for z/OS Technical Forum

OLAP specification -- RANK, DENSE_RANK, ROW_NUMBER

RANK() OVER Window ----> OLAP FunctionPARTITION BY sh.territory --- row should be assigned to partition according to territoryORDER BY sh.sales --- row sorted in the order of sales amount within each partition

Apply after Join, Predicates, Group By, HavingA new class of aggregate functions

RankDENSERANKROWNUMBER

SELECT sh.territory, sh.sales, Rank() over (PARTITION BY sh.territory ORDER BY sh.sales desc) as rank FROM sales_history;

Page 55: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

55

DB2 for z/OS Technical Forum

SELECT EMPNUM, DEPT, SALARY, RANK() OVER (ORDER BY SALARY DESC) as RANK, DENSERANK() OVER (ORDER BY SALARY DESC)as DENSERANK, ROWNUMBER() OVER (ORDER BY SALARY DESC) as ROWNUMFROM EMPLOYEE;

EMPNUM DEPT SALARY RANK DENSERANK

ROWNUM

3 - 84000 1 1 1

8 3 79000 2 2 2

6 1 78000 3 3 3

2 1 75000 4 4 4

7 1 75000 4 4 5

12 3 75000 4 4 6

10 3 55000 7 5 7

11 1 53000 8 6 8

OLAP specification -- RANK, DENSE_RANK, ROW_NUMBER

Page 56: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

56

DB2 for z/OS Technical Forum

RENAME INDEX/COLUMNWithout having to drop and recreate the objectRename Column

Rename Index

ALTER TABLE tb1 RENAME COLUMN old_columnname TO new_columnname

RENAME INDEX/TABLE old_name TO new_name

Page 57: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

57

DB2 for z/OS Technical Forum

REOPT(AUTO)We currently have REOPT(NONE), REOPT(ONCE) and REOPT(ALWAYS) for a dynamic query (with parameter marker).

REOPT(NONE) Generate access path based on default filter factor at BIND timeCache the access path

REOPT(ALWAYS)Generate access path based on real parameter marker value at each executionNo statement cache

REOPT(ONCE) Generate access path based on real parameter marker value at the first excutionCache the access path

Page 58: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

58

DB2 for z/OS Technical Forum

REOPT(AUTO)REOPT(AUTO)

Generate access path based on real parameter marker value at the first execution.Cache the access pathAt each execution, DB2 will check if the cache plan is still a good one based on the real value.A new prepare might be automatically invokedCache the newly generated access path

Page 59: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

59

DB2 for z/OS Technical Forum

Clone TableDB2 catalog

SYSTABLES (etc)MY_BASE_TABLE

MY_CLONE_TABLE

MY_IX2MY_IX2

char # date UDT_$$$LOBchar # date UDT_$$$LOB

MY_BASE_TABLELOB AUX TS

......

MY_IX1

catname.DSNDBx.MYDB1.TSPACE1.I0001.A001

. . .

MY_IX2

. . .. . .

MY_IX2

char # date UDT_$$$ LOBchar # date UDT_$$$ LOB

MY_CLONE_TABLE

LOB AUX TS

. . .

MY_IX1

. . .. . .

MY_IX1

catname.DSNDBx.MYDB1.TSPACE1.I0002.A001

...

ALTER TABLE MY_BASE TABLE ADD CLONE MY_CLONE_TABLE

Page 60: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

60

DB2 for z/OS Technical Forum

DB2 catalog

SYSTABLES (etc)MY_BASE_TABLE

MY_CLONE_TABLE

catname.DSNDBx.MYDB1.TSPACE1.I0001 .A001

. . .

MY_IX2

. . .

. . .

MY_IX2

char # date UDT_$$$LOBchar # date UDT_$$$LOB

MY_CLONE_TABLE

LOB AUX TS

. . .

MY_IX1

. . .

. . .

MY_IX1

. . .

MY_IX2

. . .

. . .

MY_IX2

char # date UDT_$$$LOBchar # date UDT_$$$ LOB

MY_BASE_TABLE

LOB AUX TS

. . .

MY_IX1

. . .

. . .

MY_IX1

catname.DSNDBx.MYDB1.TSPACE1.I0002 .A001

appl pgm

SELECT . . .

FROM MY_BASE_TABLE

EXCHANGE DATA BETWEEN MY_BASE_TABLE AND MY_CLONE_TABLE

Clone Table - EXCHANGE statement

Page 61: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

61

DB2 for z/OS Technical Forum

SpatialModeling spatial data

Spatial data typeST_POINT, ST_POLYGONE, ...

Spatial UDFCreated by DB2 when enabling V9 Spatial support

Indexing spatial dataManipulating spatial data

Spatial querySpatial predicate

CREATE DISTINCT DATA TYPE db2gse.ST_Polygone AS BLOB(2M);

CREATE FUNCTION db2gse.ST_Contains ( geometry1 db2gse.ST_Point, geometry2 db2gse.ST_Polygon) ......

Chicago

Detroit

Dallas

Houston

El Paso

AlbuquerqueSan Diego

Los Angeles

LasVegas

New Orleans

Jacksonville

Charleston

Norfolk

New YorkPhiladelphia

Bangor

Minneapolis

Omaha

Seattle

PortlandGreat Falls

LouisvilleSt. Louis

Washington, D.C.

Tulsa

Rock Springs

SiouxFalls Milwaukee

SiouxCity

Salem

Sacramento

Carson City

Boise

Helena Bismark

Pierre

Lincoln

DesMoinesCheyenne

Salt Lake City

JeffersonCity

SpringfieldIndianapolis

ColumbusCharleston

Richmond

RaleighNashville

Atlanta Columbia

TallahasseeBaton Rouge

JacksonMontgomery

Austin

Santa Fe

Phoenix

Denver

St. Paul

Madison

AugustaConcordMontpelier

AlbanyHartford Providence

Boston

Trenton

Topeka

Little RockOklahoma

City

Lansing

Frankfort

Dover

Olympia

Harrisburg

Annapolis

San Francisco

Tucson

Kansas City

Spokane

Amarillo

Corpus Christi

Brownsville

Birmingham

Tampa

Miami

Cleveland

Pittsburgh

Honolulu

Fairbanks

AnchorageValdez

JuneauSan Juan

Page 62: Microsoft PowerPoint - Day2下午_Steve Chen_DB2 V8 V9 SQL New ...

62

DB2 for z/OS Technical Forum

Spatial - cont'd

INSERT INTO CUSTOMERS (..., LOCATION) VALUES ( ..., DB2GSE.ST_POINT( ... ) ) ;

SELECT * FROM customers c, crimeZone cz WHERE db2gse.ST_within (c.Location, cz.CrimeZone) = 1;

CREATE TABLE CUSTOMERS ( ..., LOCATION DB2GSE.ST_POINT, ... ) ;

CREATE INDEX using stored procedue CALL sysproc.ST_create_index (null,'CUSTOMERS','LOCATION',.....)

Chicago

Detroit

Dallas

Houston

El Paso

AlbuquerqueSan Diego

Los Angeles

LasVegas

New Orleans

Jacksonville

Charleston

Norfolk

New YorkPhiladelphia

Bangor

Minneapolis

Omaha

Seattle

PortlandGreat Falls

LouisvilleSt. Louis

Washington, D.C.

Tulsa

Rock Springs

SiouxFalls Milwaukee

SiouxCity

Salem

Sacramento

Carson City

Boise

Helena Bismark

Pierre

Lincoln

DesMoinesCheyenne

Salt Lake City

JeffersonCity

SpringfieldIndianapolis

ColumbusCharleston

Richmond

RaleighNashville

Atlanta Columbia

TallahasseeBaton Rouge

JacksonMontgomery

Austin

Santa Fe

Phoenix

Denver

St. Paul

Madison

AugustaConcordMontpelier

AlbanyHartford Providence

Boston

Trenton

Topeka

Little RockOklahoma

City

Lansing

Frankfort

Dover

Olympia

Harrisburg

Annapolis

San Francisco

Tucson

Kansas City

Spokane

Amarillo

Corpus Christi

Brownsville

Birmingham

Tampa

Miami

Cleveland

Pittsburgh

Honolulu

Fairbanks

AnchorageValdez

JuneauSan Juan