Top Banner
SQL-PL Array Processing in DB2 Tony Andrews [email protected] Twitter
37

SQL-PL Array Processing in DB2

Apr 25, 2022

Download

Documents

dariahiddleston
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 2: SQL-PL Array Processing in DB2

Questions?

• I will try my best to get to some questions towards the end of the webinar.

• You can submit questions by typing into the questions area of your webinar control panel.

• Any questions not answered due to time constraints can be answered afterward via an email.

2

Page 3: SQL-PL Array Processing in DB2

Webinar Objectives

• Understand the key areas that can cause performance issues with DB2 queries and applications

• Better understand DB2 optimization• Understand how DB2 database design affects

performance • Understand DB2 data distribution statistics. How

does it affect performance • Understand SQL efficient coding

3

Page 4: SQL-PL Array Processing in DB2

Webinar Objectives• Objective 1: To learn the rules of coding and defining SQL-

PL variable array data types.• Objective 2: To learn about the many array functions

(ARRRAY_AGG, ARRARY_DELETE, TRIM_ARRAY, UNNEST, CARDINALITY, and more).

• Objective 3: Learn uses of the Array Constructor. • Objective 4: Learn the basic array operations like (Sub-

Indexing, Cardinality, Trimming, etc)• Objective 5: Learn how to turn a result set into an array, an

array of elements into a table, etc.).• Get empowered! New as of Db2 LUW 9.5, Db2 for I 7.1,

and z/OS V11.

4

Presenter
Presentation Notes
This presentation is to show in detail one of the many ways to help get a query to run faster. As will be shown there are many factors that can have a impact on query performance, but the one that is very powerful and totally in the hands of the developers is the query rewrite.
Page 5: SQL-PL Array Processing in DB2

What is an Array ?

• An array is a user-defined data type that consists of an ordered set of elements of a single built-in data type.

• Array entries (elements) can be accessed and modified by their index position. Going beyond the max entry gets an SQLCODE=-20439 ‘An array index with value xx is null, out of range or does not exist’

• Must first create an array datatype and then use it to define a stored procedure parameter, SQL-PL declared variable, or global variable (V12).

Presenter
Presentation Notes
The use of arrays have been around for many years in many programming languages. It’s use is to alleviate all other options for passing a list of multiple data items between programs. The use of arrays is typically easier to use and more efficient than most other options. By integrating arrays into the relational model, Db2 offers both performance and ease of use for array types. New as of Db2 LUW 9.5, Db2 for I 7.1, and z/OS V11. Going beyond the maximum cardinality of an Array is SQLCODE -20439 ‘AN ARRAY INDEX WITH VALUE xx IS NULL, OUT OF RANGE OR DOES NOT EXIST’
Page 6: SQL-PL Array Processing in DB2

Why Arrays ?

• Processing, passing, holding lists of data can often times be bulky and inefficient.

• Replaces the use of tables (either permanent or GTT)• Replaces the use of a string list variable, and then having to

unstring/decode through the list.• Replaces a long list of input/output parameters• The fact that arrays are quite common in most programming

languages. • Test have shown a performance improvement over GTTs,

Long Varchars, and returned results sets

Presenter
Presentation Notes
The use of arrays have been around for many years in many programming languages. It’s use is to alleviate all other options for passing a list of multiple data items between programs. The use of arrays is typically easier to use and more efficient than most other options. By integrating arrays into the relational model, Db2 offers both performance and ease of use for array types. New s of Db2 LUW 9.5, Db2 for I 7.1, and z/OS V11.
Page 7: SQL-PL Array Processing in DB2

SQL-PL Array Rules

• Arrays in SQL-PL are allocated and de-allocated dynamically. Memory allocation is based on the cardinality (# entries loaded into the array), and not on the possible maximum.

• All elements of array must have same data type• An array can contain a set of values, can contain no values (as

in null values), or the column with array data type can be null• Individual elements can contain a value or be null • The cardinality of the array is equal to the number of elements

in the array, not the max number that it can hold

Presenter
Presentation Notes
In some programming languages, memory allocation or storage is for the whole array’s cardinality. In Db2, when the value of an array element is null, no memory is allocated to it. It stores memory for the number of values assigned, and extends when needed.
Page 8: SQL-PL Array Processing in DB2

SQL-PL Array Rules

• Can Java handle SQL-PL Arrays? Yes via the IBM Data Server Driver for JDBC and SQLJ type 4 driver). Some code later. This was a big request from the JAVA development community.

• Can COBOL handle SQL-PL arrays? No.

• Two types of arrays: Ordinary: where items are addressed by their ordinal position within the array). Associative: where items are ordered by a defined array index value.

Presenter
Presentation Notes
When the value of an array element is null, no memory is allocated to it. This is not the case in some other programming languages.
Page 9: SQL-PL Array Processing in DB2

SQL-PL Array Definition

• Arrays are created using the CREATE TYPE command (UDT):

CREATE TYPE name AS data_type ARRAY[size]

• Includes the name of the array, data_type ARRAY, and the number of occurrences.

• The number of occurrences can be fixed or open ended:

CREATE TYPE DEPT_ARRAY AS CHAR(3) ARRAY[5] ; CREATE TYPE DEPT_ARRAY AS CHAR(3) ARRAY[] ;

Presenter
Presentation Notes
Note: DEPT_ARRAY is type name CHAR(3) is the data type for each occurrence ARRAY[5] states the DEPT_ARRAY is defined with 5 occurrences of CHAR(3) ARRAY[] states open ended number of occurrences ARRAY[5] states that the data type can have between 0 and 5 elements. It will be up to the program receiving the ARRAY data type variable to check the cardinality of the array.
Page 10: SQL-PL Array Processing in DB2

SQL-PL Array Functions

• ARRAY: Adds data elements to an array• ARRAY_AGG: Adds data elements to an by extracting data form a Db2

table • TRIM_ARRAY: Removes data elements from an array• DELETE_ARRAY: Deletes the array• UNNEST: returns a result table from the data elements in an array• CARDINALITY: Provides the number of data elements currently in an

array • MAX_CARDINALITY: Provides the maximum value specified in Create• ARRAY_FIRST: Returns the minimum array index value in the array• ARRAY_LAST: Returns the maximum array index value in the array• ARRAY_NEXT: Next element relative to current

Presenter
Presentation Notes
ARRAY: Adds elements to an array ARRAY_AGG: Adds elements to an array by extracting data from a Db2 table TRIM_ARRAY: Removes elements from an array DELETE_ARRAY: Deletes the array UNNEST: Returns a result table from elements in an array CARDINALITY: Provides the number of elements currently in an array MAX_CARDINALITY: States maximum value specified in Create statement of the array data type
Page 11: SQL-PL Array Processing in DB2

SQL-PL ARRAY Function - Example 1

---- Load an ordinary array from hard coded values. Based on: -- CREATE TYPE DEPT_LIST AS CHAR(3) ARRAY[] ; Define the type-- DECLARE V_DEPT_LIST DEPT_LIST; Use the type

• SET V_DEPT_LIST = ARRAY[‘D01’, ‘D11’, ‘D21’];

Note: Square brackets, not parenthesis

• SET V_CARDINALITY = CARDINALITY (V_DEPTNO_LIST);

V_CARDINALITY would be 3.

Presenter
Presentation Notes
Creates a datatype that can used in a parameter or variable definition.
Page 12: SQL-PL Array Processing in DB2

SQL-PL ARRAY Function - Example 2

---- Load an ordinary array from variable fields--

SET V_DEPTNO_LIST = ARRAY [V_DEPTNO1, V_DEPTNO2, V_DEPTNO3];

Presenter
Presentation Notes
Since V_DEPTNO_LIST is an array data type, the loading of 3 variable values into must have the ARRAY function on it.
Page 13: SQL-PL Array Processing in DB2

SQL-PL ARRAY Function - Example 3

---- Use a SELECT with the ARRAY function --

SET V_DEPTNO_LIST = ARRAY[SELECT DEPTNO FROM EMP];

Presenter
Presentation Notes
The ARRAY[] function be used to take output from a SQL statement and place it into an array. This makes is a lot easier than other coding techniques.
Page 14: SQL-PL Array Processing in DB2

SQL-PL ARRAY Function - Example 4

---- Use a SELECT with the ARRAY --

SET V_DEPTNO_LIST = ARRAY[SELECT DEPTNO

FROM EMPORDER BY DEPTNOFETCH FIRST 3 ROWS ONLY];

Presenter
Presentation Notes
The ARRAY[] function be used to take output from a SQL statement and place it into an array. This makes is a lot easier than other coding techniques. With the SET statement, you can use the ORDR BY and FETCH FIRST directly in the SELECT.
Page 15: SQL-PL Array Processing in DB2

SQL-PL ARRAY Function - Example 5

---- Can also use the word NULL, and a Scalar Fullselect--SET V_DEPTNO_LIST = ARRAY

[NULL, V_DEPTNO2, (SELECT DEPTNO

FROM DEPTWHERE DEPTNO LIKE ‘D%’FETCH FIRST 1 ROW ONLY)

];

Presenter
Presentation Notes
An array can have an element set to a null value, a specific variable value, or an SQL scalar function value.
Page 16: SQL-PL Array Processing in DB2

SQL-PL ARRAY_AGG Function -Example 1

---- Load up the DEPTNO array with values from the EMP table-- using a SET statement --

SET V_DEPTNO_LIST = (SELECT ARRAY_AGG(DEPTNO ORDER BY

DEPTNO)FROM DEPTWHERE DEPTNO LIKE 'D%'FETCH FIRST 3 ROWS ONLY

);

Presenter
Presentation Notes
An array can have an element set to a null value, a specific variable value, or an SQL scalar function value. ARRAY_AGG used to
Page 17: SQL-PL Array Processing in DB2

SQL-PL ARRAY_AGG Function -Example 2

---- Distinct cannot be used directly in the ARRAY_AGG Set select --

SET V_DEPTNO_LIST = (SELECT ARRAY_AGG(DEPTNO ORDER BY

DEPTNO)FROM (SELECT DISTINCT DEPTNO

FROM THEMIS90.PROJWHERE DEPTNO LIKE 'D%'FETCH FIRST 3 ROWS ONLY)

);

Presenter
Presentation Notes
Another example of setting values into an array.
Page 18: SQL-PL Array Processing in DB2

SQL-PL ARRAY_AGG Function -Example 3

---- You can select directly into …. But with some exceptions …--

SELECT ARRAY_AGG(DEPTNO)INTO V_DEPTNO_LISTFROM DEPTWHERE DEPTNO LIKE 'D%'

Presenter
Presentation Notes
Another example of setting values into an array.
Page 19: SQL-PL Array Processing in DB2

SQL-PL ARRAY_AGG Function -Example 3

---- You cannot however do a fetch first ….--

SELECT ARRAY_AGG(DEPTNO)INTO V_DEPTNO_LISTFROM DEPTWHERE DEPTNO LIKE 'D%' FETCH FIRST 3 ROWS ONLY;

Deploy Error:

stored procedure returns SQLCODE: -490, SQLSTATE: 428B7.NUMBER 3 DIRECTLY SPECIFIED IN AN SQL STATEMENT IS OUTSIDE THE RANGE OF ALLOWABLE VALUES IN Deploy failed.

Presenter
Presentation Notes
Fetch first cannot be used in direct Select Into
Page 20: SQL-PL Array Processing in DB2

SQL-PL ARRAY_AGG Function -Example 4

---- You cannot however do an order by ….--

SELECT ARRAY_AGG(DEPTNO)INTO V_DEPTNO_LISTFROM DEPTWHERE DEPTNO LIKE 'D%' ORDER BY DEPTNO;

Deploy Error:

Create stored procedure returns SQLCODE: -390, SQLSTATE: 42887.THE OBJECT ARRAY_AGG, SPECIFIC NAME *N, IS NOT VALID IN THE CONTEXT WHERE IT IS USED. SQLCODE=-390, SQLSTATE=42887, Deploy failed.

Presenter
Presentation Notes
Fetch first cannot be used in direct Select Into
Page 21: SQL-PL Array Processing in DB2

SQL-PL ARRAY_AGG Function -Example 5

---- You can however code them in a table -- expression ….--

SELECT ARRAY_AGG(DEPTNO)INTO V_DEPTNO_LISTFROM

(SELECT DEPTNO FROM THEMIS90.DEPTWHERE DEPTNO LIKE 'D%'ORDER BY DEPTNO FETCH FIRST 3 ROWS ONLY)

Deployed !!!!

Presenter
Presentation Notes
Must code Fetch First and Order By within a table expression
Page 22: SQL-PL Array Processing in DB2

SQL-PL Emptying an array

---- To empty an array --

SET V_DEPTNO_LIST = NULL; Sets the variable to null SET V_CARDINALITY =

CARDINALITY (V_DEPTNO_LIST);

V_CARDINALITY is null not 0.

SET V_DEPTNO_LIST = ARRAY[]; Empties the variableSET V_CARDINALITY =

CARDINALITY (V_DEPTNO_LIST);

V_CARDINALITY = 0.

Presenter
Presentation Notes
Note what the cardinality is when you empty an array different ways. Setting the list to NULL, the cardinality is NULL. Emptying by specifying ARRAY[]. Cardinality is 0.
Page 23: SQL-PL Array Processing in DB2

SQL-PL CARDINALITY

• CARDINALITY

SET DEPT_LIST [5] = ‘F22’; Sets the 5th element in arrayCARDINALITY would be 5.

SET V_DEPTNO = V_DEPT_LIST[6] Would get an error dueto that occurrence not existing yet. -20439 SQLCODE

What if? SET V_DEPT_LIST [7] = ‘G22’; and then …

SET V_DEPTNO = V_DEPT_LIST[6] V_DEPT set to nulls!

Presenter
Presentation Notes
If DEPT_LIST is set to an open ended number of elements, and an element is skipped (in this example the 6th occurrence), it gets defaulted to nulls. If you have an open ended array, and you only set the 5th occurrence to a value, then the cardinality will be 5. The first 4 values will be nulls. Note: Array sub-indexing is performed using the familiar square bracket syntax,
Page 24: SQL-PL Array Processing in DB2

SQL-PL UNNEST Example 1The UNNEST treats the array like a table

SELECT COUNT(*) INTO P_OUT_COUNTFROM EMP WHERE DEPTNO IN

(SELECT IN.DEPT FROM UNNEST(P_DEPTNO_LIST) ASIN(DEPT))

;

Presenter
Presentation Notes
This is an example of how to use an array of values in an SQL IN List predicate by using the UNNEST function on the P_DEPTNO_LIST array datatype. The UNNEST treats the array like a table to fetch data from.�
Page 25: SQL-PL Array Processing in DB2

SQL-PL UNNEST WITH ORDINALITYExample 2

CREATE TABLE DEPT_EMEA

( POSITION INT,DEPTNO CHAR(3)

) ;

INSERT INTO DEPT_EMEA(DEPTNO, POSITION) SELECT * FROM UNNEST(V_DEPTNO_LIST) WITH ORDINALITYAS (DEPTNO, POSITION)

;

SELECT *FROM DEPT_EMEA;

POSITION DEPTNO------------- ----------

1 D012 D113 D21

Presenter
Presentation Notes
The WITH ORDINALITY clause can be used in the UNNESTing of data elements from an array. This will get the index number (integer data type) returned also of each element returned from the array.
Page 26: SQL-PL Array Processing in DB2

SQL-PL UNNEST Example 3

SELECT P.PROJNO, P.PROJNAMEFROM PROJ P,

UNNEST(P_DEPTPNO_LIST) AS V(DEPTNO)WHERE P.DEPTNO = V.DEPTNO

Presenter
Presentation Notes
In this example, UNNEST takes an array and produces a one-column table V with column DEPTNO.
Page 27: SQL-PL Array Processing in DB2

SQL-PL Associative Arrays

• Arrays in SQL-PL that assign a unique key to a value • No maximum cardinality is defined (open ended)• Create statement needs to have index datatype specified

• Must be integer or varchar (or you get SQLCODE=-20436)• The associative array index values do not have to be ordered

• Can be sparse• Each element in the array can be referenced by an associated

index valueCREATE TYPE STATES_ARRAY AS VARCHAR(16)

ARRAY[VARCHAR(02)];

Presenter
Presentation Notes
This defines an associative array for storing state codes and their state names. The index VARCHAR(02) will contain the state code and used as the index while the elements of VARCHAR(16) will contain the state names.
Page 28: SQL-PL Array Processing in DB2

SQL-PL Associative Arrays

CREATE TYPE STATES_ARRAY AS VARCHAR(16)

ARRAY[VARCHAR(02)];

• The data type VARCHAR(16) after the AS keyword refers to the data values (in this case state names) stored in the array. Ex: ‘Ohio’, ‘Alabama’, etc..

• The ARRAY[VARCHAR(02)] indicates that this is an associative array and will contain the index values. For this example ‘OH’, ‘AL’, etc.

Presenter
Presentation Notes
This defines an associative array for storing state codes and their state names. The index VARCHAR(02) will contain the state code and used as the index while the elements of VARCHAR(16) will contain the state names.
Page 29: SQL-PL Array Processing in DB2

SQL-PL Associative Arrays

• The order in which values are assigned to array elements in an associative array does not matter, but they will be re-ordered in the order of the index values: For example:

DECLARE V_STATE_NAMES STATES_ARRAY;

SET V_STATE_NAMES['OH'] = 'Ohio';SET V_STATE_NAMES['AL'] = 'Alabama';SET P_STATE_INDEX = ARRAY_FIRST(V_STATE_NAMES);

P_STATE_INDEX will equal ‘AL’

Presenter
Presentation Notes
After creating an associative array datatype called of STATES_ARRAY, you can them declare a variable with this datatype. Here a variable called V_STATE_NAMES is declared, then loaded with 2 values (‘OH’ and ‘AL’) which will automatically be ordered by the index values. You can prove that by executing the ARRAY_FIRST function. The ARRAY_FIRST will get you the index value.
Page 30: SQL-PL Array Processing in DB2

SQL-PL Associative Arrays

• How do we get the state names out of the array after they are loaded? You need to have an index state code value, with hard coded or from a variable. For example:

DECLARE V_STATE_NAMES STATES_ARRAY;

SET V_STATE_NAMES['OH'] = 'Ohio';SET V_STATE_NAMES['AL'] = 'Alabama';

SET P_STATE_NAME = V_STATE_NAMES['OH'];

P_STATE_NAME will equal ‘Ohio’

Presenter
Presentation Notes
After creating an associative array datatype called of STATES_ARRAY, you can them declare a variable with this datatype. Here a variable called V_STATE_NAMES is declared, then loaded with 2 values (‘OH’ and ‘AL’) which will automatically be ordered by the index values. You can then use the index value to pull a value from the array to set into another variable or in this example a parameter.
Page 31: SQL-PL Array Processing in DB2

SQL-PL Associative Arrays

• What if we try to set a variable or parameter with a value using and index value that does not exists in the table? For example:

SET P_STATE_NAME = V_STATE_NAMES[‘XX'];

SQLCODE -20439 AN ARRAY INDEX WITH VALUE XX IS NULL, OUT OF RANGE OR DOES NOT EXIST

SET P_STATE_NAME = V_STATE_NAMES[‘oh']; Note lowercase

SQLCODE -20439 AN ARRAY INDEX WITH VALUE oh IS NULL, OUT OF RANGE OR DOES NOT EXIST

Presenter
Presentation Notes
Same out of range error -204439 will occur if you try to access an entry with an index value that is not in the array.
Page 32: SQL-PL Array Processing in DB2

SQL-PL Arrays and Java

• Java programs must accesses the DB2 for z/OS server via the IBM Data Server Driver for JDBC and SQLJ type 4 driver

• To pass an array to a stored procedure, use the createArrayOf() method of the Connection object• Creates a java.sql.Array object of the specified type

• Use the underlying datatype of the array element• Do not try to use the UDT name

• The first example that follows accepts an array as it's first parameter

• The example following that one returns an array as it's 2nd

parameter

Presenter
Presentation Notes
Calling a SQL-PL stored procedure with a parameter of an array datatype can only be dome via another SQL-PL stored procedure or a Java program that accesses the DB2 for z/OS server via the IBM Data Server Driver for JDBC and SQLJ type 4 driver.
Page 33: SQL-PL Array Processing in DB2

SQL-PL V12 Enhancements z/OS

• Db2 11 provided support for the array data type• Db2 also allows for global variables, but not defined as an array• Db2 12 provides for using an associative array as an argument to

the ARRAY_AGG function

Presenter
Presentation Notes
Page 34: SQL-PL Array Processing in DB2

Thank you for allowing me and Themis to share some of our experience and

knowledge today!

Tony Andrews [email protected]

I hope that you learned something new today !!!!

Presenter
Presentation Notes
Page 35: SQL-PL Array Processing in DB2

The material in this presentation is further developed in the following Themis courses:

DB1029 – Exploiting SQL-PL Native Stored Procedures on z/OS

DB1028 – DB2 LUW SQL-PL Stored Procedure Development

DB1070 – Advanced Query, Native Stored Procedures, and Query Tuning on DB2 for z/OS

Links to these courses may be found at: www.themisinc.com

Tony’s Email: [email protected]: @ThemisTraining

Page 36: SQL-PL Array Processing in DB2

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

www.ibmpress.comwww.amazon.com

Page 37: SQL-PL Array Processing in DB2

Education. Check Outwww.themisinc.com

• On-site and Public• Instructor -led• Hands-on• Customization • Experience• Over 30 DB2

courses• Over 400 IT courses

US 1-800-756-3000Intl. 1-908-233-8900

Presenter
Presentation Notes