Subqueries
When you need to narrow your search condition based on information in an interim table, you can use a subquery. For example, you might want to find all employee numbers in one table that also exist for a given project in a second table.
Conceptual overview of subqueries
SELECT EMPNO, LASTNAME, COMM
FROM DSN8D10.EMP
WHERE EMPNO
⋮
However, you cannot proceed because the DSN8D10.EMP table does not include project number data. You do not know which employees are working on project MA2111 without issuing another SELECT statement against the DSN8D10.EMPPROJACT table.
SELECT EMPNO, LASTNAME, COMM
FROM DSN8D10.EMP
WHERE EMPNO IN
(SELECT EMPNO
FROM DSN8D10.EMPPROJACT
WHERE PROJNO = 'MA2111');
- Db2 evaluates the subquery
to obtain a list of EMPNO values:
The result is in an interim result table, similar to the one in the following output:(SELECT EMPNO FROM DSN8D10.EMPPROJACT WHERE PROJNO = 'MA2111');
from EMPNO ===== 200 200 220
- The interim result table then serves as a list in the search condition
of the outer SELECT. Effectively, Db2 executes
this statement:
SELECT EMPNO, LASTNAME, COMM FROM DSN8D10.EMP WHERE EMPNO IN ('000200', '000220');
As a consequence, the result table looks similar to the following output:EMPNO LASTNAME COMM ====== ======== ==== 000200 BROWN 2217 000220 LUTZ 2387
Correlated and uncorrelated subqueries
Subqueries supply information that is needed to qualify a row (in a WHERE clause) or a group of rows (in a HAVING clause). The subquery produces a result table that is used to qualify the row or group of selected rows.
SELECT EMPNO, LASTNAME, COMM
FROM DSN8D10.EMP
WHERE EMPNO IN
(SELECT EMPNO
FROM DSN8D10.EMPPROJACT
WHERE PROJNO = 'MA2111');
Subqueries that vary in content from row to row or group to group are correlated subqueries. For information about correlated subqueries, see Correlated subqueries.
Subqueries and predicates
operand operator (subquery)
WHERE X IN (subquery1) AND (Y > SOME (subquery2) OR Z IS NULL)
Subqueries can also appear in the predicates of other subqueries. Such subqueries are nested subqueries at some level of nesting. For example, a subquery within a subquery within an outer SELECT has a nesting level of 2. Db2 allows nesting down to a level of 15, but few queries require a nesting level greater than 1.
The relationship of a subquery to its outer SELECT is the same as the relationship of a nested subquery to a subquery, and the same rules apply, except where otherwise noted.
The subquery result table
SELECT EMPNO, LASTNAME
FROM DSN8D10.EMP
WHERE SALARY =
(SELECT AVG(SALARY)
FROM DSN8D10.EMP);
SELECT EMPNO, LASTNAME
FROM DSN8D10.EMP
WHERE (SALARY, BONUS) IN
(SELECT AVG(SALARY), AVG(BONUS)
FROM DSN8D10.EMP);
Except for a subquery of a basic predicate, the result table can contain more than one row. For more information, see Places where you can include a subquery.