SELECT name, salary
FROM employees
WHERE salary > ANY (
SELECT salary
FROM employees
WHERE department_id = 2
);
SELECT name, salary
FROM employees
WHERE salary > ALL (
SELECT salary
FROM employees
WHERE department_id = 2
);
| Aspect | ANY | ALL |
|---|---|---|
| Meaning | TRUE if condition matches at least one value | TRUE if condition matches every value |
| Typical Use Case | Compare against the smallest value in a set (similar to MIN) | Compare against the largest value in a set (similar to MAX) |
| Performance | May stop scanning once a match is found | Must evaluate the entire subquery result |
| NULL Handling | NULL values can prevent matchesβclean your data | Any NULL in the subquery can make the comparison UNKNOWN |
Imagine a products table:
| id | price | category |
|---|---|---|
| 1 | 100 | A |
| 2 | 200 | A |
| 3 | 150 | B |
SELECT *
FROM products
WHERE price > ANY (
SELECT price
FROM products
WHERE category = 'A'
);
β
Returns products with price > 100 (or any value in category A). Product 3 is included.
SELECT *
FROM products
WHERE price > ALL (
SELECT price
FROM products
WHERE category = 'A'
);
β
Returns products with price > 200. Only products priced higher than everyone in category A are returned.