You are on page 1of 9

IBM Systems Lab Services and Training

QTEMP and SQL


Hernando Bedoya
hbedoya@us.ibm.com
IBM Systems Lab Services
Db2 for i Team

IBM Systems Lab Services – January 2019 Copyright 2019 IBM Corporation
IBM Systems Lab Services and Training

QTEMP and SQL not the best mix

IBM Systems Lab Services – January 2019 Copyright 2019 IBM Corporation
SQL 1 SQL 2 SQL 3
Query QTEMP Query QTEMP Query

Multiple SQL Statements

IBM Systems Lab Services – January 2019 Copyright 2019 IBM Corporation
Query Query Query

Single SQL Statement SQL1

IBM Systems Lab Services – January 2019 Copyright 2019 IBM Corporation
Problem to Solve

The list of customers who were in the “top 10” for two

consecutive years? 2018 and 2019.

IBM Systems Lab Services – January 2019 Copyright 2019 IBM Corporation
Using QTEMP – Logical Step-by-Step and Work
Tables
DECLARE GLOBAL TEMPORARY TABLE t1 AS
(SELECT customer_name, SUM(sales) FROM SALES
WHERE YEAR=2018
GROUP BY customer_name
ORDER BY SUM(sales) DESC
FETCH FIRST 10 ROWS ONLY);

DECLARE GLOBAL TEMPORARY TABLE t2 AS


(SELECT customer_name, SUM(sales) FROM SALES
WHERE YEAR=2019
GROUP BY customer_name
ORDER BY SUM(sales) DESC
FETCH FIRST 10 ROWS ONLY;

SELECT T1.customer_name,
T1.total_sales AS sales2018, T2.total_sales AS sales2019
FROM T1 INNER JOIN T2
ON T1.customer_name = T2.customer_name;
IBM Systems Lab Services – January 2019 Copyright 2019 IBM Corporation
CTEs – Thinking in Sets …
• What if you want the list of customers who were in the “top 10” for two
consecutive years? Think in sets …

WITH top10_2018 (customer_name, total_sales) AS


(SELECT customer_name, SUM(sales) FROM SALES
WHERE YEAR=2018
GROUP BY customer_name
ORDER BY SUM(sales) DESC
FETCH FIRST 10 ROWS ONLY) ,
top10_2019 (customer_name, total_sales) AS
(SELECT customer_name, SUM(sales) FROM SALES
WHERE YEAR=2019
GROUP BY customer_name
ORDER BY SUM(sales) DESC
FETCH FIRST 10 ROWS ONLY)
SELECT Y1.customer_name,
Y1.total_sales AS sales2018, Y2.total_sales AS sales2019
FROM top10_2018 Y1 INNER JOIN top10_2019 Y2
ON Y1.customer_name = Y2.customer_name

IBM Systems Lab Services – January 2019 Copyright 2019 IBM Corporation
Db2 for i
SQE Plan Cache

SQL Program A
Access
Plan 1 Statement 1

Statement 2
Access
Statement 3
Plan 2

Access
Plan 3

IBM Systems Lab Services – January 2019 Copyright 2019 IBM Corporation
Db2 for i
SQE Plan Cache

SQL Program A
Access
Plan 1 Statement 1

Statement 2
Access
Statement 3
Plan 2

Access
Plan 3
SQL Program B

Access
Plan 4 Statement 4

IBM Systems Lab Services – January 2019 Copyright 2019 IBM Corporation

You might also like