Decorrelation & SELECT-Clause Risks in SQL
Once-not-per-row — the optimization instinct
Correlated subqueries logically re-execute per outer row — O(rows × inner). Planners decorrelate simple shapes to joins/semi-joins; engineers rewrite the rest manually (JOIN+GROUP, windows). Scalar SELECT-clause subqueries are N+1-shaped at scale with multi-row runtime risk and NULL-on-empty. One scalar is clarity; five is an incident — prefer LEFT JOIN to pre-aggregated derived tables.
Spot per-row
EXPLAIN loops/dependent subplans = correlated shape. Cost N × inner.
Rewrite to set
JOIN (SELECT key, AVG… GROUP BY key) or window — executed once.
Defuse SELECT-clause
Scalar per-row lookups → LEFT JOIN pre-agg derived. Five scalars is an incident.
Guarantee singularity
Aggregation, LIMIT 1, or uniqueness proof — or runtime multi-row errors.
1-- correlated (per row) → decorrelated (single join+group):2-- SELECT name, (SELECT AVG(salary) FROM employees e2 WHERE e2.department = e1.department) FROM employees e1;3-- ===>4SELECT e.name, t.avg_pay FROM employees e JOIN (SELECT department, AVG(salary) AS avg_pay FROM employees GROUP BY department) t ON t.department = e.department;
| form | cost |
|---|---|
| correlated | per-row probes |
| decorrelated | single grouped join |
Same answers, different plans: N probes collapse to one hash/group. Recognizing the shape in EXPLAIN triggers the rewrite before it pages.
Dept average: per-row → grouped join
Same answers, one grouped pass.
1-- correlated:2-- SELECT name, (SELECT AVG(salary) FROM employees e2 WHERE e2.department = e1.department) FROM employees e1;3-- decorrelated:4SELECT e.name, t.avg_pay FROM employees e JOIN (SELECT department, AVG(salary) AS avg_pay FROM employees GROUP BY department) t ON t.department = e.department;
| name | dept_avg |
|---|---|
| Alice | 83000 |
| Bob | 55000 |
SELECT-subquery bulk fix
Per-row COUNTs become one LEFT JOIN.
1-- risky:2-- SELECT c.name, (SELECT COUNT(*) FROM orders o WHERE o.customer_id = c.id) FROM customers c;3-- safe:4SELECT c.name, COALESCE(t.n, 0) FROM customers c LEFT JOIN (SELECT customer_id, COUNT(*) AS n FROM orders GROUP BY customer_id) t ON t.customer_id = c.id;
| customer | orders |
|---|---|
| Ada | 3 |
| Bo | 0 |
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.