Derived Tables & ANY / ALL in SQL
Shape-then-join; compare against every value
A FROM subquery (derived table) produces a named temporary relation — alias mandatory — that the outer query treats as a table: pre-aggregate, filter, then join. ANY/SOME compare against at least one value (= ANY is IN); ALL compares against every value (> ALL means above the max). NULLs in the set poison NOT IN and ALL to UNKNOWN.
Derived shapes first
FROM (SELECT …) builds a named temp relation. Alias mandatory.
Join the shape
Outer query treats it as a table — pre-aggregated, fan-out-proof.
ANY is one, ALL is every
= ANY is IN. > ALL means above the max. NULLs poison ALL/NOT IN.
CTE when nested
Same power, better names + multi-reference. Past one level prefer WITH.
1SELECT d.dept_id, t.avg_pay FROM departments d JOIN (SELECT department, AVG(salary) AS avg_pay FROM employees GROUP BY department) t ON t.department = d.dept_id;
| dept_id | avg_pay |
|---|---|
| Engineering | 83000 |
| Sales | 55000 |
| Marketing | 47000 |
The derived table pre-aggregates to one row per department, then joins cleanly — no fan-out. The same shape with > ALL would compare each salary against every value in the set.
Pre-aggregate then join
One row per key before widening.
1SELECT d.dept_id, t.avg_pay FROM departments d JOIN (SELECT department, AVG(salary) AS avg_pay FROM employees GROUP BY department) t ON t.department = d.dept_id;
| dept_id | avg_pay |
|---|---|
| Engineering | 83000 |
| Sales | 55000 |
| Marketing | 47000 |
> ALL means above max
Quantifier comparison beyond equality.
1SELECT name FROM employees WHERE salary > ALL (SELECT salary FROM employees WHERE department = 'Sales');
| name |
|---|
| Alice |
| Cynthia |
| Farid |
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.