Learn SQL
-- subqueries.decorrelation_rewrite

Decorrelation & SELECT-Clause Risks in SQL

Once-not-per-row — the optimization instinct

--concept

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.

--how it works
1

Spot per-row

EXPLAIN loops/dependent subplans = correlated shape. Cost N × inner.

2

Rewrite to set

JOIN (SELECT key, AVG… GROUP BY key) or window — executed once.

3

Defuse SELECT-clause

Scalar per-row lookups → LEFT JOIN pre-agg derived. Five scalars is an incident.

4

Guarantee singularity

Aggregation, LIMIT 1, or uniqueness proof — or runtime multi-row errors.

--visualization
JOIN (SELECT dept, AVG…) — one hash/group, same answers
namedept_avg
Alice83000
Bob55000
Stage 1 / 1
SELECT-clause scalars are N+1-shaped — LEFT JOIN pre-agg derived instead.
--example
query.sql
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;
Result
formcost
correlatedper-row probes
decorrelatedsingle grouped join

Same answers, different plans: N probes collapse to one hash/group. Recognizing the shape in EXPLAIN triggers the rewrite before it pages.

--variants

Dept average: per-row → grouped join

Same answers, one grouped pass.

query.sql
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;
Result
namedept_avg
Alice83000
Bob55000
1Inner once computed per department, not per employee.
2Join fans back without replication (unique keys).
3Window AVG() OVER (PARTITION BY …) is the row-detail twin.

SELECT-subquery bulk fix

Per-row COUNTs become one LEFT JOIN.

query.sql
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;
Result
customerorders
Ada3
Bo0
1N customers triggered N COUNT probes.
2Grouped derived runs once; LEFT keeps zero-order customers.
3COALESCE renders missing as 0.
--key facts
Per-row pricecorrelation expressiveness at N× cost
RewriteJOIN+GROUP or window form
SELECT-subqueryone is clarity, five is incident
--use cases
Slow-correlated triage from EXPLAIN loops
N+1-shaped SELECT lists in reporting queries
--under the hood
Planners auto-decorrelate simple EXISTS/IN to semi-joins; complex aggregates resist — manual rewrite wins.
LATERAL is explicit per-row by design — decorrelation does not apply; index the inner path.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Take the queries you just visualized and see the data structures that power real databases.