Baltimore Adv SQL
Baltimore Adv SQL
Problem #7:
Distinct Options
Distinct often times causes sorts to take place of the final result set to look for and
eliminate any duplicate rows. At times, there are choices that can also handle
duplicates without executing the Distinct.
2012 Themis, Inc. All rights reserved.
39
2012 Themis, Inc. All rights reserved.
Option #1: Distinct Options
SELECT DISTINCT E.EMPNO, E.LASTNAME
FROM EMP E, EMPPROJ ACT EPA
WHERE E.EMPNO =EPA.EMPNO
Or
SELECT E.EMPNO, E.LASTNAME
FROM EMP E, EMPPROJ ACT EPA
WHERE E.EMPNO =EPA.EMPNO
GROUP BY E.EMPNO, E.LASTNAME
Distinct to get
rid of duplicates
PROBLEM #7: Find employees who are currently working
on a project or projects.
Group By to get
rid of duplicates
Option #1
There are sort enhancements for both Distinct and Group By with no column
function. This was already available prior to V9 with Group By and a column
function. It now handles the duplicates more efficiently in the input phase,
elimination a step 2 passing of data to a sort merge.
Prior to V9, Distinct could only use a unique index to avoid a sort. Group By could
use both unique and non unique. Now V9 Distinct may take advantage of non unique
indexes to avoid a sort in order to handle duplicates.
Sometimes, if one of the tables has no columns being selected from it, it can then be
moved to a subquery.
DB2 Advanced SQL Working with Complex Queries
40
2012 Themis, Inc. All rights reserved.
2012 Themis, Inc. All rights reserved.
Option #2: Distinct Options
SELECT E.EMPNO, E.LASTNAME
FROM EMP E
WHERE E.EMPNO IN
(SELECT EMPNO
FROM EMPPROJ ACT EPA)
In
non correlated
subquery
PROBLEM #7: Find employees who are currently working
on a project or projects.
Option #2
This In subquery will build a list of values for the EMP In predicate, and sort those
values in ascending order at the same time
as getting rid of duplicate values.
New in V9 are optimizer enhancements that sometimes takes an In subquery and:
- Materialize the list of values into a workfile, and feeds the EMP table in a Nested
Loop Join Process
- Transforms the In non correlated subquery to a correlated subquery.
V9 calls this Global query Optimization
2012 Themis, Inc. All rights reserved.
41
2012 Themis, Inc. All rights reserved.
Option #3: Distinct Options
SELECT E.EMPNO, E.LASTNAME
FROM EMP E
WHERE EXISTS
(SELECT 1
FROM EMPPROJ ACT EPA
WHERE EPA.EMPNO =E.EMPNO)
Exists
correlated
subquery
PROBLEM #7: Find employees who are currently working
on a project or projects.
Option #3
This Exists subquery will be checked for each employee in the EMP table. A flag gets
sent on the join stating for each employee value whether that value exists or not in the
EMPPROJACT table.
Because the subquery will get executed multiple times, you want to make sure an
index exists on the join column(s).
DB2 Advanced SQL Working with Complex Queries
42
2012 Themis, Inc. All rights reserved.
2012 Themis, Inc. All rights reserved.
Set Operations
Union / Union All
Intersect / Intersect All
Except / Except All
Set Operations
SQL Supports three set operations for combining and comparing the results of two
selects. UNION combines two result sets vertically. INTERSECT and EXCEPT may
be used for comparing two results vertically. All three operations require that the
result sets being processed are compatible, that is, they have the same number of
columns and compatible data types.
2012 Themis, Inc. All rights reserved.
43
2012 Themis, Inc. All rights reserved.
SELECT LASTNAME
FROM NA_EMP
INTERSECT
SELECT LASTNAME
FROM SA_EMP
Intersect / Intersect ALL
Finds records where all
selected columns match
Order of the tables with
INTERSECT does not
matter.
Intersect
Both of the following queries will return the same results.
1) SELECT LASTNAME
FROM NA_EMP
INTERSECT
SELECT LASTNAME
FROM SA_EMP
2) SELECT LASTNAME
FROM SA_EMP
INTERSECT
SELECT LASTNAME
FROM NA_EMP
DB2 Advanced SQL Working with Complex Queries
44
2012 Themis, Inc. All rights reserved.
2012 Themis, Inc. All rights reserved.
Intersect / Intersect ALL
SELECT #1 SELECT #2
Abbot Baker
Jones Jones
Smith Jones
Smith Smith
Smith Smith
INTERSECT INTERSECT ALL
X
X
LASTNAME
J ones
Smith
LASTNAME
J ones
Smith
Smith
This example demonstrates the difference between INTERSECT and INTERSECT
ALL. Since Smith occurs three times in the first select but only twice in the second,
INTERSECT ALL considers that there are two matches.
Once again, a duplicate is considered any record in the result where the values for all
selected columns are the same.
2012 Themis, Inc. All rights reserved.
45
2012 Themis, Inc. All rights reserved.
SELECT N.LASTNAME SELECT S.LASTNAME
FROM NA_EMP N FROM SA_EMP S
WHERE EXISTS WHERE EXISTS
(SELECT 1 (SELECT 1
FROM SA_EMP S FROM NA_EMP N
WHERE S.LASTNAME WHERE N.LASTNAME
= N.LASTNAME = S>LASTNAME)
Exists 1 . Exists 2
LASTNAME
J ones
Smith
Smith
Smith
Smith
LASTNAME
J ones
J ones
Smith
Smith
Other Options
Intersect is not the same as Exists logic as can be seen in the example. Exists checks
one at a time whereas the intersect logic looks at all of the same name as a group in
each table and compares.
DB2 Advanced SQL Working with Complex Queries
46
2012 Themis, Inc. All rights reserved.
2012 Themis, Inc. All rights reserved.
Except / Except ALL
SELECT #1 SELECT #2
Abbot Baker
Jones Jones
Smith Jones
Smith Smith
Smith Smith
EXCEPT
EXCEPT ALL
LASTNAME
Abbot
LASTNAME
Abbot
Smith
Except
This example demonstrates the difference between EXCEPT and EXCEPT ALL. Smith
is not returned using EXCEPT, since there are Smiths in the second result. Using
EXCEPT ALL, however, one Smith is returned since there were three in the first
result, but only two in the second.
Notice that EXCEPT and EXCEPT ALL will produce a different result if the SELECTs
are reversed. Order is important!
2012 Themis, Inc. All rights reserved.
47
2012 Themis, Inc. All rights reserved.
SELECT N.LASTNAME SELECT S.LASTNAME
FROM NA_EMP N FROM SA_EMP S
WHERE NOT EXISTS WHERE NOT EXISTS
(SELECT 1 (SELECT 1
FROM SA_EMP S FROM NA_EMP N
WHERE S.LASTNAME WHERE N.LASTNAME
= N.LASTNAME = S>LASTNAME)
Not Exists 1 . Not Exists 2
LASTNAME
Abbot
LASTNAME
Baker
Other Options
DB2 Advanced SQL Working with Complex Queries
48
2012 Themis, Inc. All rights reserved.
2012 Themis, Inc. All rights reserved.
SELECT FROM MERGE
SELECT ITEMNAME, UPD_IND FROM FINAL TABLE
(MERGE INTO ITEM I
INCLUDE (UPD_IND CHAR(1))
USING (VALUES (1, 'SOCKET') )
AS NEWITEM (ITEMNO, ITEMNAME)
ON I.ITEMNO = NEWITEM.ITEMNO
WHEN MATCHED THEN
UPDATE SET ITEMNAME = NEWITEM.ITEMNAME,
UPD_IND = 'U'
WHEN NOT MATCHED THEN
INSERT (ITEMNO,ITEMNAME,UPD_IND)
VALUES (NEWITEM.ITEMNO, NEWITEM.ITEMNAME,'I') )
SELECT from MERGE
When using from a MERGE statement, it may be desirable to determine whether an
INSERT or UPDATE operation was performed. This may be accomplished by using
the INCLUDE clause to create an indicator variable. In the example shown, an
INCLUDE column is created called UPD_IND. When an update is performed, the
UPD_IND is set to a U. When an insert is performed, the UPD_IND is set to an I.
This value may be returned to the application via the SELECT.
2012 Themis, Inc. All rights reserved.
49
2012 Themis, Inc. All rights reserved.
Counting With CASE
SELECT SEX, COUNT(*)
FROM EMP
GROUP BY SEX
SEX 2
F 14
M 19
Provide a list of total number of males and total
number of females.
CASE Statement
The CASE statement may be used in conjunction with column functions to translate
ranges of values into categories. In this example, CASE is being used to supply a
value of 1 or 0 for 3 separate columns in a result set that are then summed.
DB2 Advanced SQL Working with Complex Queries
50
2012 Themis, Inc. All rights reserved.
2012 Themis, Inc. All rights reserved.
Counting With CASE
SELECT
SUM(CASE WHEN SEX = F THEN 1 ELSE 0 END)
AS NUM_FEMALES,
SUM(CASE WHEN SEX = M THEN 1 ELSE 0 END)
AS NUM_MALES
FROM EMP
NUM_FEMALES NUM_MALES
14 19
Provide a list of total number of males and total
number of females.
Counting with CASE
2012 Themis, Inc. All rights reserved.
51
2012 Themis, Inc. All rights reserved.
Counting With CASE
SELECT
SUM (CASE WHEN SALARY < 20000
THEN 1 ELSE 0 END ) AS LOW,
SUM (CASE WHEN SALARY BETWEEN 20000 AND 45000
THEN 1 ELSE 0 END ) AS MID,
SUM (CASE WHEN SALARY > 45000
THEN 1 ELSE 0 END ) AS HI
FROM EMP
LOW MID HI
7 23 3
DB2 Advanced SQL Working with Complex Queries
52
2012 Themis, Inc. All rights reserved.
2012 Themis, Inc. All rights reserved.
Table Pivoting
SELECT JOB,
SUM(CASE WHEN DEPTNO = 'A00' THEN 1 ELSE 0 END) AS A00,
SUM(CASE WHEN DEPTNO = 'B01' THEN 1 ELSE 0 END) AS B01,
SUM(CASE WHEN DEPTNO = 'C01' THEN 1 ELSE 0 END) AS C01,
SUM(CASE WHEN DEPTNO = 'D11' THEN 1 ELSE 0 END) AS D11,
SUM(CASE WHEN DEPTNO = 'D21' THEN 1 ELSE 0 END) AS D21,
SUM(CASE WHEN DEPTNO = 'E01' THEN 1 ELSE 0 END) AS E01,
SUM(CASE WHEN DEPTNO = 'E11' THEN 1 ELSE 0 END) AS E11,
SUM(CASE WHEN DEPTNO = 'E21' THEN 1 ELSE 0 END) AS E21
FROM EMP
GROUP BY JOB
JOB A00 B01 C01 D11 D21 E01 E11 E21
ANALYST 0 0 2 0 0 0 0 0
CLERK 1 0 0 0 5 0 0 0
DESIGNER 0 0 0 8 0 0 0 0
FIELDREP 0 0 0 0 0 0 0 3
MANAGER 0 1 1 1 1 1 1 1
OPERATOR 0 0 0 0 0 0 4 0
PRES 2 0 0 0 0 0 0 0
SALESREP 1 0 0 0 0 0 0 0
Table Pivoting
The CASE expression may also be used in conjunction with column functions to
change a result from a vertical to horizontal display. In this example a GROUP BY on
JOB, DEPTNO would have provided one row for each combination of JOB and
DEPTNO with a count. If a tabular result is desired with one columns values as the
columns on the table and another for the rows, the result may be pivoted with the
CASE statement. CASE must be used to evaluate every desired department.
2012 Themis, Inc. All rights reserved.
53
2012 Themis, Inc. All rights reserved.
New DB2 V8 SQL Features
Following are some of the new SQL features in DB2 V8:
1) More Stage 1 predicates
2) Multi Row Fetch, Update, and Insert
3) Multiple Distincts
4) Expressions in the Group By
5) Common Table Expression
6) Dynamic Scrollable Cursors
7) Sequences versus Identity Columns
8) Materialized Query Tables (MQTs)
9) Recursive SQL
10) More efficient use of indexes. Forward and Backward scans
11) New XML functions and datatypes
12) New Get Diagnostics for warning and error information
13) Select from an Insert statement
14) Scalar Fullselect within a Select, Case, Update, etc.
DB2 V8 Features
DB2 Advanced SQL Working with Complex Queries
54
2012 Themis, Inc. All rights reserved.
2012 Themis, Inc. All rights reserved.
New DB2 V9 SQL Features
Following are some of the new SQL features in DB2 V9:
1) Set operations Intersect and Except
2) Merge statement for Upsert processing. Insert or Update
3) OLAP features for Ranking and Numbering of data
4) Native SQL Stored Procedures
5) Instead of Triggers
6) New support and SQL for XML data
7) Optimization Service Center (OSC)
8) Distinct sort avoidance with non unique indexes
9) Indexing on Expressions
10) Statistics on Views
11) Skipped locked data
12) Truncate statement
DB2 9 Features
Native SQL: No C compilation. Fully integrated into DB2, Versioning
Instead of Triggers: Used on views.
Truncate: Options to bypass and delete triggers, Drop its storage. Fast delete. Useful
when deleting tables on a nightly basis for nightly refreshes. Very fast delete.
Skip Locked Data: You can use the SKIP LOCKED DATA option with cursor stability
(CS) isolation and read stability (RS) isolation. However, you cannot use SKIP
LOCKED DATA with uncommitted read (UR) or repeatable read (RR) isolation levels.
2012 Themis, Inc. All rights reserved.
55
2012 Themis, Inc. All rights reserved.
New DB2 V9 SQL Features
Following are some of the new SQL features in DB2 V9:
13) Array host variables now supported for stored procedures
14) Timestamp auto update for inserts and Updates
15) Optimistic locking
16) New DECFLOAT datatype
17) Select from Update or Delete getting old or new values
18) Fetch First, Order BY within subqueries
19) REOPT AUTO (Dynamic SQL)
20) Data Studio for Native Stored Procedures
Optimistic locking: Built in timestamp automatically updated by DB2. Allows for
checking that a row has not changed when updating from the last time it was selected.
REOPT Auto: The ideas behind REOPT(AUTO) is to come up with the optimal access
path in the minimum number of prepares.
DB2 Advanced SQL Working with Complex Queries
56
2012 Themis, Inc. All rights reserved.
2012 Themis, Inc. All rights reserved.
New DB2 V10 SQL Features
Following are some of the new SQL features in DB2 V10:
1) OLAP Moving Sum, Count, and Average
2) Extended Null Indicators
3) New timestamp Precisions
4) Currently Committed Data
5) SQL Pl Enhancements
6) XML Enhancements
7) Row Permissions
8) Column Masking
9) Temporal Tables
DB2 10 Features
2012 Themis, Inc. All rights reserved.
57
2012 Themis, Inc. All rights reserved.
Training and Consulting. Check Out
www.themisinc.com
On-site and Public
Instructor -led
Hands-on
Customization
Experience
Over 25 DB2 courses
Over 400 IT courses
US 1-800-756-3000
Intl. 1-908-233-8900
DB2 Advanced SQL Working with Complex Queries
58
2012 Themis, Inc. All rights reserved.
2012 Themis, Inc. All rights reserved.
Finally! A book of DB2 SQL tuning tips for
developers, specifically designed to
improve performance.
DB2 SQL developers now have a handy
reference guide with tuning tips to
improve performance in queries,
programs and
applications.
Education. Check out
www.db2sqltuningtips.com
2012 Themis, Inc. All rights reserved.
59
2012 Themis, Inc. All rights reserved.
Thank You for allowing us at Themis
to share some of our experience
and knowledge!
We hoped that you learned something new today
We hope that you are a little more inspired to code with
performance in mind
I have noticed that when the developers get
educated, good SQL programming standards are in
place, and program walkthroughs are executed
correctly, incident reporting stays low, CPU costs do not
get out of control, and most performance issues are
found before promoting code to production.
DB2 Advanced SQL Working with Complex Queries
60
2012 Themis, Inc. All rights reserved.
This Page Intentionally Left Blank