List most critical tips from DB2 SQL Tuning Tips for z/OS Developers
Stay Away from Distinct if Possbile Details:
group by
orin or exists subquery
if duplicates due to one-to-many relationshipTry Rewriting Range Predicates as Between Predicates
12WHERE HIREDATE > :HV-DATEWHERE HIREDATE BETWEEN :HV-DATE and '9999-12-31'Use Tools for Monitoring Details: Some of the most common z/OS DB2 monitoring tools are OMEGAMON®, TMon, MainView, Apptune, Insight for DB2, and DB2PM. Some of the most common DB2 LUW monitoring tools are IBM’s Optim™ Query Tuner, Precise for DB2, Quest, DBI Software, Embarcadero’s Performance Analyst, and ITGAIN.
Avoid Discrepancies with Non-Column Expressions
12WHERE EDLEVEL = 123.45 * 12WHERE EDLEVEL = SMALLINT(ROUND(123.45*12,0))Ensure That Subquery Predicates Involving Min and Max Have the Possibility of Nulls Being Returned Handled
Always Code For Fetch Only or For Read Only with Cursor Processing When a Query Is Only Selecting Data
Avoid Selecting a Row from a Table to Help Decide Whether the Logic in the Code Should Execute an Update or an Insert
Use the DB2 V9 MERGE Statement
Keep Table and Index Files Healthy and Organized Details: SYSIBM.SYSTABLESPACESTATS and SYSIBM.SYSINDEXSPACESTATS tables
Consider OLTP Front-End Processing
1OPTIMIZE FOR 14 ROWSTake Advantage of Materialized Query Tables to Improve Response Time (Dynamic SQL Only)
1234567891011121314151617181920CREATE TABLE DEPT_SUM_MQT_TABLE AS(SELECT WORKDEPT, AVG(SALARY) AS AVG_SAL,AVG(BONUS) AS AVG_BONUSAVG(COMM) AS AVG_COMM,SUM(SALARY) AS SUM_SAL,SUM(BONUS) AS SUM_BONUSSUM(COMM) AS SUM_COMMFROM EMPGROUP BY WORKDEPT)DATA INITIALLY DEFERRED REFRESH DEFERREDMAINTAINED BY SYSTEMENABLE QUERY OPTIMIZATION;--original querySELECT SUM(BONUS)FROM EMPWHERE WORKDEPT = 'A00'--rewrite by optimizeSELECT AVG_BONUSFROM DEPT_SUM_MQT_TABLEWHERE WORKDEPT = 'A00'Insert with Select
123456SELECT EMPNO, LASTNAME, MIDINIT, FIRSTNME,DEPTNO, SALARY, BONUS, COMMFROM FINAL TABLE(INSERT (EMPNO, LASTNAME, MIDINIT, FIRSTNME, DEPTNO)VALUES ('123456', 'SMITH', 'A', 'JOE', 'A00'))Identify Times for Volatile Tables Details: Using the VOLATILE keyword on the Create or Alter Table statement identifies tables whose data volumes fluctuate.
1234CREATE TABLE EMP_TEMP(EMPNO CHAR(6) Not Null,LASTNAME VARCHAR(15) Not Null )VOLATILEUse the ON COMMIT DROP Enhancement
12345678DECLARE GLOBAL TEMPORARY TABLESESSION.EMP_TEMP1 (COL1 CHAR (20)COL2 CHAR (10)COL3 SMALLINT )ON COMMIT DROP TABLEON COMMIT DELETE ROWSON COMMIT PRESERVE ROWSUse Multiple Distincts Details: This is an automatic performance gain that alleviates the need for separate calls to DB2.
123SELECT SUM (DISTINCT SALARY),AVG(DISTINCT BONUS)FROM EMP;Take Advantage of Backward Index Scanning Details: For each column that is in the Order By clause, the ordering that is specified in the index has to be exactly the opposite of the ordering that is specified in the Order By clause.
Set Your Clustering Index Correctly
Take Advantage of DB2 V8 Enhanced DISCARD Capabilities When It Comes to Mass Deletes
Consider Parallelism https://www-01.ibm.com/support/knowledgecenter/SSEPEK_11.0.0/com.ibm.db2z11.doc.perf/src/tpc/db2z_enableparallelprocess.dita
Consider Direct Row Access Using ROWID Datatype (V8) or RID Function (V9) Details: If the ROWID value is then used in the search condition of subsequent updates or deletes, DB2 may navigate directly to the row, bypassing any index processing or tablespace scans.
1EMP_ID ROWID NOT NULL GENERATED ALWAYSSpecify the Leading Index Columns in WHERE Clauses Details: For a composite index, the following query would use the index and execute matching processing as long as the leading column of the index is specified in the WHERE clause.
Keep in Mind Index Only Processing Whenever Possible Many times, developers code queries that need to execute one of the four column aggregate functions (Sum, Avg, Min, or Max). They can get some great results by including an extra column as part of an index. Take, for example, the following query and associated index, Index1 = (YEAR, PERIOD):
DB2 is good at recognizing the JRNL_AMT column in the index, even though there is no specific predicate on it, and it will choose index only processing.123SELECT SUM(JRNL_AMT)FROM LEDGER_TABLEWHERE YEAR = 2008 AND PERIOD IN (1,2,3)Take Advantage of DB2 V9 Optimistic Locking
123456789CREATE TABLE EMP(EMPNO CHAR(6) NOT NULL,.........EMP_UPD TIMESTAMP NOT NULLGENERATED BY DEFAULTFOR EACH ROW ON UPDATEAS ROW CHANGE TIMESTAMP))Use the DB2 V9 MERGE Statement https://www-01.ibm.com/support/knowledgecenter/SSEPGG_9.7.0/com.ibm.db2.luw.sql.ref.doc/doc/r0010873.html
Code Boolean Term Predicates Whenever Possible Details: A Boolean term predicate is a predicate that is connected by And logic, so when one predicate is evaluated as false for a row, it then makes the entire Where clause evaluate to false.
12345678910SELECT EMPNO, LASTNAME, SALARYFROM EMPWHERE (LASTNAME > 'SMITH')OR (LASTNAME = 'SMITH' and FIRSTNME > 'BOB')SELECT EMPNO, LASTNAME, SALARYFROM EMPWHERE LASTNAME >= 'SMITH'AND (LASTNAME > 'SMITH' OR(LASTNAME = 'SMITH' AND FIRSTNME > 'BOB'))Avoid Sorts with Order By Details: DB2 may avoid sorts if there are leading columns in an index to match the Order By or if the query contains an equal predicate on the leading column(s) of an index.
Watch Out for Case Logic
Details: If most of the rows have a Salary < 50000.00, then that piece of logic should be coded first.123456SELECT EMPNO, LASTNAME, SALARY,CASE WHEN SALARY < ...WHEN SALARY > ...ELSEENDFROM EMPKnow Your Version of DB2
12SELECT GETVARIABLE('SYSIBM.VERSION')FROM SYSIBM.SYSDUMMY1If You Need True Uniqueness, Try the V8 Generate_Unique Function
12345678910CREATE TABLE ORDER_TBL(ORDER_ID CHAR(13) FOR BIT DATA,ORDER_DATE DATE,ORDER_LOC CHAR(03) );INSERT INTO ORDER_TBLVALUES(GENERATE_UNIQUE(), CURRENT DATE, 'NY');SELECT TIMESTAMP(ORDER_ID), ORDER DATE, ....FROM ORDER_TBL;Update and Delete with Select (V9) Details: The words Old Table are SQL DB2 reserved words that need to be coded in order for this statement to work.
12345678910SELECT SALARY, BONUSFROM OLD TABLE(UPDATE EMPSET SALARY = :HV1-SALARY,BONUS = :HV2-BONUSWHERE EMPNO = :HV-EMPNO)SELECT LASTNAME, FIRSTNME, WORKDEPTFROM OLD TABLE(DELETE FROM EMPWHERE EMPNO = :HV-EMPNO)Avoid Unnecessary Sorting Details: Data sorting can be caused by Group By, Order By, Distinct, Union, Intersect, Except, and Join processing.
List most critical tips of store procedure related from DB2 SQL Tuning Tips for z/OS Developers