Sub topic 10
Multi-column subqueries
A multi-column subquery returns more than one column, and the outer query compares several columns at once. This chapter assumes you can write single-row and multi-row subqueries with =, IN, ANY and ALL, and that you know GROUP BY and aggregates. The examples use the Oracle HR sample schema (EMPLOYEES, DEPARTMENTS).
The problem a single column cannot solve
Suppose you want the highest-paid employee in each department. A first attempt compares only the salary:
SELECT last_name, department_id, salary
FROM employees
WHERE salary IN (SELECT MAX(salary)
FROM employees
GROUP BY department_id);This query runs, but it is wrong. The subquery returns a list of salaries with no department attached. An employee in department 50 is returned if their salary equals the maximum of any department. The department and the salary must match together as a pair.
Comparing a column list
Put the outer columns in parentheses and make the subquery return the same number of columns, in the same order:
SELECT last_name, department_id, salary
FROM employees
WHERE (department_id, salary) IN (SELECT department_id, MAX(salary)
FROM employees
GROUP BY department_id);For each outer row, Oracle builds the pair (department_id, salary). The row qualifies if that pair equals at least one row of the subquery result. Because the match is on the pair, the query returns the top earner of each department. If two people tie for the maximum in the same department, both rows are returned.
The rules for the column list:
- The number of columns on the left must equal the number of columns in the subquery's
SELECTlist. Otherwise Oracle raisesORA-00913: too many valuesorORA-00947: not enough values. - Columns are matched by position, not by name.
(department_id, salary)compared withSELECT MAX(salary), department_id ...pairs a department with a salary and fails or returns nothing useful. - The data types of each pair of positions must be compatible, in the same way as for a single-column comparison.
Pairwise and non-pairwise comparison
The form above is a pairwise comparison: all columns must match the same subquery row. You can instead write one single-column subquery per column and join them with AND. This is a non-pairwise comparison, because each column is tested against its own result set.
The next two queries use the same inner logic. They find employees who have the same manager and the same department as employee 199 or employee 174.
-- Pairwise: manager and department must come from the same row
SELECT employee_id, manager_id, department_id
FROM employees
WHERE (manager_id, department_id) IN
(SELECT manager_id, department_id
FROM employees
WHERE employee_id IN (199, 174))
AND employee_id NOT IN (199, 174);
-- Non-pairwise: each column is checked independently
SELECT employee_id, manager_id, department_id
FROM employees
WHERE manager_id IN
(SELECT manager_id
FROM employees
WHERE employee_id IN (199, 174))
AND department_id IN
(SELECT department_id
FROM employees
WHERE employee_id IN (199, 174))
AND employee_id NOT IN (199, 174);In the second query, an employee can have the manager of employee 199 and the department of employee 174. Each column finds a match in its own list, so the row passes even though no single source row has that combination. The non-pairwise form can therefore return more rows than the pairwise form. It can never return fewer.
| Property | Pairwise | Non-pairwise |
|---|---|---|
| Syntax | `(a, b) IN (SELECT a, b ...)` | `a IN (...) AND b IN (...)` |
| Number of subqueries | One | One per column |
| Match requirement | Same subquery row for all columns | Each column matches some row |
| Typical meaning | A combined key such as department and maximum salary | Independent filters that happen to use subqueries |
Choose pairwise when the columns form one logical key. Choose non-pairwise only when the conditions really are independent.
Single-row form with `=`
When the subquery is guaranteed to return one row, you can use = with a column list:
SELECT last_name, job_id, salary
FROM employees
WHERE (job_id, salary) = (SELECT job_id, salary
FROM employees
WHERE employee_id = 141);This returns every employee who has the same job and the same salary as employee 141, including employee 141 themselves. If the subquery returns more than one row, Oracle raises ORA-01427: single-row subquery returns more than one row. Use IN when the row count is not guaranteed to be one.
Multi-column subqueries and NULLs
A comparison of column lists is true only when every column comparison is true. If any column comparison involves a NULL and no other column comparison is false, the result is unknown, and a row with an unknown result is not returned.
This has a visible effect in the top-earner query. In the HR schema one employee has no department (department_id is NULL). The GROUP BY in the subquery forms a group for that NULL department and returns a pair such as (NULL, 7000). In the outer query, the comparison NULL = NULL is unknown, so that employee never matches and is missing from the result, even though they are the top earner of their group.
To include such rows, compare with EXISTS and handle NULL explicitly:
SELECT e.last_name, e.department_id, e.salary
FROM employees e
WHERE e.salary = (SELECT MAX(i.salary)
FROM employees i
WHERE i.department_id = e.department_id
OR (i.department_id IS NULL AND e.department_id IS NULL));The correlated subquery makes the NULL case explicit. The OR branch matches the NULL department with itself.
NOT IN with column lists behaves differently from single-column NOT IN. A list row containing a NULL in one column does not block the whole result, as it does in the single-column trap. It blocks an outer row only when all the other columns in that list row equal the outer row's values, because false AND unknown is false. A quick test is still worthwhile: when the data can contain NULL, write NOT EXISTS instead.
Alternatives to a multi-column subquery
A multi-column IN can be rewritten two ways. Each has a reason to prefer it.
Correlated subquery:
SELECT e.last_name, e.department_id, e.salary
FROM employees e
WHERE e.salary = (SELECT MAX(i.salary)
FROM employees i
WHERE i.department_id = e.department_id);Analytic function in an inline view:
SELECT last_name, department_id, salary
FROM (SELECT last_name, department_id, salary,
RANK() OVER (PARTITION BY department_id
ORDER BY salary DESC) AS rnk
FROM employees)
WHERE rnk = 1;| Approach | Strength | Caution |
|---|---|---|
| Multi-column `IN` | Short, reads as "this pair appears in that set" | Drops rows whose key columns are `NULL` |
| Correlated subquery | Easy to adapt for `NULL` keys | Written per row, so check the plan on large tables |
| `RANK()` in an inline view | Reads the table once and handles ties | Needs a nested query to filter on `rnk` |
The multi-column IN form is a good default when you read the table once for the inner query and the key columns are never NULL.
Common errors
- Mismatched column counts raise
ORA-00913orORA-00947. Count the columns on both sides. - Columns in the wrong order give wrong data or a type error such as
ORA-01722: invalid number. - Using
=with a subquery that returns several rows raisesORA-01427. - Expecting
NULLkeys to match. They do not, in eitherINor=. - Using non-pairwise conditions when the columns are a combined key. The query runs and returns extra rows with no error.
Exercise
You run this query and it returns no rows, although you expect some: SELECT last_name FROM employees WHERE (department_id, manager_id) IN (SELECT manager_id, department_id FROM employees WHERE employee_id = 141);. Name the mistake and write the corrected query.
Show answer
The columns are matched by position, and the subquery lists them in the opposite order, so department IDs are compared with manager IDs. The corrected query is SELECT last_name FROM employees WHERE (department_id, manager_id) IN (SELECT department_id, manager_id FROM employees WHERE employee_id = 141);.
Exercise
Write a query that returns the employees who have the lowest salary in their job, using a multi-column subquery. Then say what happens to an employee whose job_id is NULL.
Show answer
SELECT last_name, job_id, salary FROM employees WHERE (job_id, salary) IN (SELECT job_id, MIN(salary) FROM employees GROUP BY job_id);. An employee with a NULL job_id is not returned, because the comparison of NULL with NULL is unknown, so the pair never matches.