SQL EXISTS / ANY / ALL
These keywords are used with subqueries to perform advanced comparisons.
Letβs break them down simply:
πΉ EXISTS β Check if Subquery Returns Rows
Returns TRUE if the subquery returns at least one row.
SELECT department_name
FROM departments d
WHERE EXISTS (
SELECT 1
FROM employees e
WHERE e.department_id = d.department_id
);β Lists departments that have employees.
πΉ ANY β Compare with Any Matching Value
Returns TRUE if at least one value from the subquery meets the condition.
SELECT employee_name, salary
FROM employees
WHERE salary > ANY (
SELECT salary
FROM employees
WHERE department_id = 50
);β Fetches employees earning more than at least one employee in dept 50.
You can also use: = ANY (equivalent to IN), <> ANY, < ANY, etc.
πΉ ALL β Compare with All Values
Returns TRUE if the condition holds true for every value from the subquery.
SELECT employee_name, salary
FROM employees
WHERE salary > ALL (
SELECT salary
FROM employees
WHERE department_id = 50
);β Fetches employees earning more than everyone in dept 50.
π§ Quick Recap
| Keyword | Purpose | Returns TRUE if… |
|---|---|---|
EXISTS | Subquery returns any row | At least one row is found |
ANY | Comparison true for at least one | Condition matches one or more values |
ALL | Comparison true for every value | Condition matches all values in subquery |
π‘ Use these for powerful filtering when comparing against multiple rows.
