Sub topic 3
Multi-row Subqueries: IN, ANY and ALL
Assume you know basic SELECT, WHERE, joins, and aggregate functions. You should also know the Oracle HR tables EMPLOYEES and DEPARTMENTS.
A multi-row subquery returns zero, one, or many values. The outer query uses a multi-row comparison operator to test those values.
For example, this subquery returns the department IDs of employees earning more than 10,000:
SELECT department_id
FROM employees
WHERE salary > 10000;Because several employees may match, the subquery can return several department IDs. Use IN when the outer value should match at least one value in that result.
SELECT department_name
FROM departments
WHERE department_id IN (
SELECT department_id
FROM employees
WHERE salary > 10000
);The outer query returns departments that contain at least one employee earning more than 10,000.
Choosing the comparison operator
| Operator | Meaning | Typical question |
|---|---|---|
| `IN` | Equals one of the returned values | Is this department in the result set? |
| `ANY` | Satisfies the comparison with at least one returned value | Is this salary higher than at least one value? |
| `ALL` | Satisfies the comparison with every returned value | Is this salary higher than every value? |
SOME is a synonym for ANY.
Use ANY with an explicit comparison operator:
SELECT last_name, salary
FROM employees
WHERE salary > ANY (
SELECT salary
FROM employees
WHERE department_id = 30
);This returns employees whose salary is higher than at least one salary in department 30. For a nonempty result, > ANY is effectively a comparison with the smallest returned salary.
ALL requires the comparison to succeed for every value:
SELECT last_name, salary
FROM employees
WHERE salary > ALL (
SELECT salary
FROM employees
WHERE department_id = 30
);This returns employees whose salary is higher than every salary in department 30. For a nonempty result, > ALL is effectively a comparison with the largest returned salary.
Avoiding a single-row error
Do not use = when the subquery can return several rows:
-- This can fail with ORA-01427.
SELECT last_name
FROM employees
WHERE department_id = (
SELECT department_id
FROM employees
WHERE salary > 10000
);= expects one value, but the inner query may return many. Replace it with IN when any matching value is acceptable:
SELECT last_name
FROM employees
WHERE department_id IN (
SELECT department_id
FROM employees
WHERE salary > 10000
);The optimizer may transform these forms internally, so choose the operator that states the intended meaning clearly.
Exercise
Which operator should replace the equals sign when a subquery may return several department IDs and the outer row should match any of them?
Show answer
Use IN.