Sub topic 5
Comparing against a set with ANY and ALL
This chapter assumes you can write a basic SELECT with WHERE, you know aggregate functions, and you understand NULL and three-valued logic (a condition can be true, false, or unknown). You should also be comfortable with scalar subqueries (one value) and multi-row subqueries used with IN.
Why ANY and ALL exist
A scalar subquery returns one value, so you can write salary > (SELECT ...). If that subquery returns several rows, the database raises an error, because > cannot compare one value to a list.
IN handles lists, but only for equality. ANY and ALL extend a comparison operator (=, <>, <, <=, >, >=) so it works against a set of values returned by a subquery.
The general form is:
expression comparison_operator ANY (subquery)
expression comparison_operator ALL (subquery)The subquery must return exactly one column. It can return any number of rows.
How ANY works
x > ANY (subquery) is true if the comparison is true for at least one value in the set. Think of it as a chain of OR conditions, one per row the subquery returns.
Suppose department 10 has salaries 3000, 4000, and 5000. Then salary > ANY (...) behaves like this:
salary > 3000 OR salary > 4000 OR salary > 5000This is the same as salary > 3000, the smallest value. So > ANY means "greater than the minimum" and < ANY means "less than the maximum".
SELECT name, salary
FROM employees
WHERE salary > ANY (SELECT salary FROM employees WHERE department_id = 10);This returns every employee paid more than at least one person in department 10.
How ALL works
x > ALL (subquery) is true only if the comparison is true for every value in the set. It behaves like a chain of AND conditions.
SELECT name
FROM employees
WHERE salary > ALL (SELECT salary FROM employees WHERE department_id = 10);The subquery returns every salary in department 10. The outer query keeps only employees paid more than the highest of them, so > ALL means "greater than the maximum" and < ALL means "less than the minimum".
The following table summarizes the equivalences when the subquery returns at least one row and no NULLs.
| Expression | Equivalent to |
|---|---|
| `x > ANY (s)` | `x > (SELECT MIN(...))` |
| `x < ANY (s)` | `x < (SELECT MAX(...))` |
| `x > ALL (s)` | `x > (SELECT MAX(...))` |
| `x < ALL (s)` | `x < (SELECT MIN(...))` |
| `x = ANY (s)` | `x IN (s)` |
| `x <> ALL (s)` | `x NOT IN (s)` |
Equivalent forms with aggregates
Because > ANY and > ALL reduce to the minimum and maximum, you can often write the same query with an aggregate and a scalar subquery:
SELECT name
FROM employees
WHERE salary > (SELECT MAX(salary) FROM employees WHERE department_id = 10);This is equivalent to the > ALL example, with two differences. First, it is usually easier to read. Second, it behaves differently when the subquery returns no rows or contains NULL, as the next sections show. Many developers prefer the aggregate form for exactly this reason, and use ANY and ALL when the intent of "compare to a set" reads naturally.
Edge case: an empty set
The two operators give opposite results on an empty set.
x > ANY (empty)is false, because no value satisfies the comparison.x > ALL (empty)is true, because no value violates it. This is called vacuous truth.
The aggregate form behaves differently: MAX of no rows is NULL, so salary > NULL is unknown and the row is not returned.
-- Department 999 does not exist.
SELECT name
FROM employees
WHERE salary > ALL (SELECT salary FROM employees WHERE department_id = 999);This query returns every employee, since there is nothing to exceed. If you expected an empty result, this is a common surprise. When a department can be empty, use the aggregate form or add an explicit check.
Edge case: NULL in the set
NULL values in the subquery result make the outcome unknown, and a WHERE clause keeps only rows where the condition is true.
For ANY:
- If at least one comparison is true, the result is true, even if other values are NULL.
- If none is true but some comparison is unknown (because of NULL), the result is unknown, so the row is dropped.
- If all comparisons are false, the result is false.
For ALL:
- If at least one comparison is false, the result is false.
- If none is false but some comparison is unknown, the result is unknown, so the row is dropped.
- If all comparisons are true, the result is true.
Here is a runnable example that shows the effect. It works in PostgreSQL, which supports ANY and ALL with a subquery and with VALUES.
CREATE TEMP TABLE scores (player text, points int);
INSERT INTO scores VALUES ('a', 10), ('b', 20), ('c', NULL);
-- Returns no rows: 25 > 10 and 25 > 20 are true, but 25 > NULL is unknown.
SELECT 'x' AS result
WHERE 25 > ALL (SELECT points FROM scores);
-- Returns one row: 25 > 10 is true, so ANY is true regardless of NULL.
SELECT 'x' AS result
WHERE 25 > ANY (SELECT points FROM scores);The first query returns nothing even though 25 is larger than every actual score. The NULL makes the whole ALL condition unknown. This is the same mechanism behind the NOT IN trap covered in the previous chapter, because <> ALL is how NOT IN is defined.
To protect against NULL, filter it out inside the subquery:
SELECT 'x' AS result
WHERE 25 > ALL (SELECT points FROM scores WHERE points IS NOT NULL);Using ANY and ALL with other operators
You can pair ANY and ALL with any comparison operator, not only > and <.
= ANYmeans "equals at least one value", the same asIN.<> ALLmeans "differs from every value", the same asNOT IN.<> ANYmeans "differs from at least one value". This is almost always true when the set has two or more distinct values, so it is rarely what people intend. A common mistake is to write<> ANYwhen<> ALL(that is,NOT IN) was meant.
-- Employees outside department 10 and 20 salaries: probably not what you want
SELECT name
FROM employees
WHERE salary <> ANY (SELECT salary FROM employees WHERE department_id IN (10, 20));If the two departments have at least two different salaries, every employee satisfies this condition, because any salary differs from at least one of them.
Portability
Support for ANY and ALL with a subquery is broad: PostgreSQL, MySQL, SQL Server, Oracle, and SQLite-compatible engines vary, so check yours. SQLite does not support ANY or ALL with a subquery, so use the aggregate form or IN and NOT IN there. SQL Server and Oracle accept SOME as a synonym for ANY. PostgreSQL also lets you use = ANY (array) with an array value, which is a separate feature from subqueries.
When to choose which form
- Use
INandNOT INfor plain equality, and remember the NULL trap forNOT IN. - Use
> ALLor< ALLwhen the idea "beats everyone in this group" is the clearest description of the question. - Use
> ANYor< ANYfor "beats at least one". The aggregate form (> MIN,< MAX) is often more direct. - Use an aggregate scalar subquery when the set could be empty and you want NULL semantics rather than vacuous truth.
Exercise
Department 10 has salaries 3000, 4000, and 5000. An employee earns 4500. Does salary > ANY (...) return true? Does salary > ALL (...) return true? Then say what each would return if department 10 had no employees.
Show answer
4500 > ANY is true, because 4500 > 3000 (at least one comparison is true). 4500 > ALL is false, because 4500 > 5000 is false. If department 10 had no employees, > ANY would be false (no value satisfies the comparison) and > ALL would be true (no value violates it).
Exercise
A query SELECT name FROM products WHERE price < ALL (SELECT price FROM competitor_prices) returns no rows, although several products are clearly cheaper than every competitor price you can see. What is the most likely cause, and how do you fix it?
Show answer
The competitorprices.price column probably contains a NULL. The comparison with NULL is unknown, so < ALL is never true for any row. Fix it by filtering inside the subquery: `WHERE price < ALL (SELECT price FROM competitorprices WHERE price IS NOT NULL). Alternatively, use price < (SELECT MIN(price) FROM competitor_prices)`, since MIN ignores NULL.