softwaretips4u Tips that Transform
← Back to Homepage ← Back to Articles

SQL ANY vs ALL Operators

πŸ”Ή 1. The ANY Operator

SELECT name, salary
FROM employees
WHERE salary > ANY (
  SELECT salary
  FROM employees
  WHERE department_id = 2
);
πŸ‘‰ Finds employees who earn more than at least one person in department 2.

πŸ”Ή 2. The ALL Operator

SELECT name, salary
FROM employees
WHERE salary > ALL (
  SELECT salary
  FROM employees
  WHERE department_id = 2
);
πŸ‘‰ Finds employees who earn more than every employee in department 2 (higher than the max salary in department 2).

πŸ”Ή 3. Key Differences

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

πŸ”Ή 4. Practical Product Example

Imagine a products table:

id price category
1 100 A
2 200 A
3 150 B

Query with ANY

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.

Query with ALL

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.

πŸ’‘ Tip: Use indexes on the filtered columns inside subqueries to keep ANY and ALL comparisons performant, especially on large tables.
← Back to Articles | 🏠 Back to Homepage