Sub topic 3
Multi-row subqueries: IN, ANY and ALL
This chapter assumes you can write SELECT, WHERE and GROUP BY queries, join two tables, and use aggregates such as AVG and MAX. The examples use the Oracle HR sample schema (EMPLOYEES and DEPARTMENTS). It also assumes you know what a single-row subquery is and why = fails when the subquery returns more than one row.
Why a second kind of operator is needed
A single-row subquery returns at most one value, so you can compare against it with =, <, > and the other ordinary operators. Many questions have more than one answer, though. "Which departments have an employee earning over 10000?" can match several departments.
If you put a multi-row subquery behind =, Oracle stops with an error:
SELECT department_name
FROM departments
WHERE department_id = (SELECT department_id
FROM employees
WHERE salary > 10000);This raises ORA-01427: single-row subquery returns more than one row. The fix is to use an operator that accepts a set of values. Oracle has three of them: IN, ANY (or its synonym SOME) and ALL.
IN: is the value in the set?
IN is true when the left-hand value equals at least one value the subquery returns.
SELECT department_name
FROM departments
WHERE department_id IN (SELECT department_id
FROM employees
WHERE salary > 10000);The subquery returns a list of department IDs, and one department ID can appear many times. Duplicates do no harm. IN only asks whether a match exists, so each department is returned once.
Compare this with a join. A join between departments and employees would return one row per matching employee, so a department with five high earners would appear five times. IN keeps one row per outer row without needing DISTINCT.
NOT IN is the opposite, and it has a serious problem with NULLs. A later chapter covers that trap in detail. For now, remember that the subquery behind a NOT IN must never return a NULL.
ANY and SOME: compare against at least one value
ANY is always used together with a comparison operator: = ANY, > ANY, < ANY, <> ANY and so on. The condition is true when the comparison holds for at least one value in the set.
| Expression | Meaning |
|---|---|
| `x = ANY (set)` | x equals at least one value. Same as `x IN (set)`. |
| `x > ANY (set)` | x is greater than at least one value, so greater than the minimum. |
| `x < ANY (set)` | x is less than at least one value, so less than the maximum. |
| `x <> ANY (set)` | x differs from at least one value. |
The > ANY and < ANY rows are the ones that surprise people. "Greater than some value" means "greater than the smallest value". Suppose a subquery returns 5000, 7000 and 9000. Then salary > ANY (...) is true for any salary above 5000.
SELECT last_name, salary
FROM employees
WHERE salary > ANY (SELECT salary
FROM employees
WHERE department_id = 30);This returns employees who earn more than the lowest-paid person in department 30. It is equivalent to salary > (SELECT MIN(salary) ...).
<> ANY is a common source of bugs. With the set 5000, 7000, 9000, the value 7000 is different from 5000, so 7000 <> ANY (...) is true. In fact <> ANY is true for almost every value unless the set holds a single distinct value. If you mean "not equal to any of them", you want NOT IN or <> ALL.
ALL: compare against every value
ALL is also used with a comparison operator. The condition is true only when the comparison holds for every value in the set.
| Expression | Meaning |
|---|---|
| `x > ALL (set)` | x is greater than every value, so greater than the maximum. |
| `x < ALL (set)` | x is less than every value, so less than the minimum. |
| `x = ALL (set)` | x equals every value. This is true only if the set has one distinct value. |
| `x <> ALL (set)` | x differs from every value. Same as `x NOT IN (set)`. |
SELECT last_name, salary
FROM employees
WHERE salary > ALL (SELECT salary
FROM employees
WHERE department_id = 30);This returns employees who earn more than the highest-paid person in department 30. It compares against the maximum of the set.
The next table shows how the same operators behave on the set {5000, 7000, 9000}.
| Left value | `> ANY` | `> ALL` | `< ANY` | `< ALL` |
|---|---|---|---|---|
| 4000 | false | false | true | true |
| 6000 | true | false | true | false |
| 10000 | true | true | false | false |
A value between the minimum and the maximum, such as 6000, is the case where ANY and ALL give different answers.
Equivalent forms with MIN and MAX
For inequality comparisons, ANY and ALL are shortcuts for an aggregate. You can often write the same query with a single-row subquery, which some readers find clearer.
-- Same result as: salary > ALL (...)
SELECT last_name, salary
FROM employees
WHERE salary > (SELECT MAX(salary)
FROM employees
WHERE department_id = 30);The two forms differ when the subquery returns no rows. That case is covered next.
Edge cases
The subquery returns no rows
An empty set gives opposite results for the two operators. x > ANY (empty set) is false, because no value satisfies the comparison. x > ALL (empty set) is true, because no value fails it.
If department 30 had no employees, the > ALL query above would return every employee. The MAX form would return none, because MAX over no rows is NULL and salary > NULL is unknown. Check which behavior you want before you swap one form for the other.
The subquery returns NULL
If the set contains a NULL, comparisons against that value are unknown, not false. Oracle keeps a row only when the whole condition is true.
x = ANY (...)andx IN (...)still return true when another value matches. A NULL in the set does no harm here.x > ALL (...)becomes unknown as soon as the set contains a NULL, because the comparison with the NULL is neither true nor false. The query returns no rows.x <> ALL (...)andx NOT IN (...)also return no rows. This is the NOT IN trap.
If your subquery can return NULL, filter it out with WHERE column IS NOT NULL inside the subquery.
ANY with a single row
If the subquery returns one row, = ANY, IN and = all behave the same. Oracle does not raise ORA-01427 for IN, ANY and ALL, whatever the number of rows.
Choosing the operator
- Use
INto test membership in a set. It is the most readable choice for equality. - Use
> ANYor< ANYwhen "beats at least one" is the real requirement. Say it withMINorMAXif that reads better. - Use
> ALLor< ALLwhen "beats every one" is the requirement. - Prefer
NOT EXISTSoverNOT INwhen the subquery could return NULL.
Putting it together
A multi-row subquery can sit in a HAVING clause too. This query lists departments whose average salary exceeds the average salary of every department with ID 50 or 60. Here the subquery returns one row per department, so it needs ALL.
SELECT department_id, AVG(salary) AS avg_sal
FROM employees
GROUP BY department_id
HAVING AVG(salary) > ALL (SELECT AVG(salary)
FROM employees
WHERE department_id IN (50, 60)
GROUP BY department_id);Read it from the inside. The subquery produces two averages, one for department 50 and one for department 60. The outer HAVING keeps only groups whose average beats both.
Exercise
A subquery returns the salaries 4000, 6000 and 8000. For each condition, say whether a salary of 6000 satisfies it: (a) salary > ANY (subquery), (b) salary > ALL (subquery), (c) salary = ANY (subquery), (d) salary <> ANY (subquery).
Show answer
(a) True, because 6000 is greater than 4000. (b) False, because 6000 is not greater than 6000 or 8000. (c) True, because 6000 equals one of the values, so it is the same as IN. (d) True, because 6000 differs from 4000 and 8000. This shows why <> ANY is rarely what you want.
Exercise
Write a query that returns the last name and salary of employees who earn less than every employee in department 90. Then say what the query returns if department 90 has no employees.
Show answer
SELECT lastname, salary FROM employees WHERE salary < ALL (SELECT salary FROM employees WHERE departmentid = 90); If department 90 has no employees, the subquery returns an empty set, so < ALL is true for every row and the query returns all employees.