Learn SQL
-- subqueries.correlated_subquery

Correlated Subqueries in SQL

An inner query that references the outer row

--concept

A correlated subquery mentions a column of the outer query, so it cannot run once on its own — it is (conceptually) re-evaluated per outer row. That makes it expressive (“compare each employee to their department’s average”) but potentially slow: naive engines re-run it N times. Good optimisers decorrelate into a join; you should still know what you are asking for.

--how it works
1

Alias the outer table

FROM employees e — the alias is what the inner query will reference.

2

Reference it inside

(SELECT MAX(salary) FROM employees i WHERE i.department = e.department) — e.department is the correlation.

3

Per-row evaluation (conceptually)

For each employee, the inner query runs with that row’s department bound — N inner executions for N outer rows.

4

The comparison decides

The outer WHERE compares the row against its group’s inner result — per-department max, average, latest, whatever the inner query computes.

5

Benchmark against the join

The same logic is often a JOIN + GROUP BY or a window function. Optimisers may decorrelate automatically — EXPLAIN tells you whether they did.

--visualization
outer: employees eAlice85kBob52kCynthia91kDavid47kElena58kFarid73kinner: MAX(salary) FROM employees i WHERE i.department =e.department (correlation)press Run — the inner query re-runs for every outer rowtoppers so far…—
outer row being evaluated department topper (kept)
Stage 1 / 8
For each outer employee row, the inner query re-runs with THAT row’s department bound to i.department.
--example
query.sql
1SELECT e.name, e.department, e.salary
2FROM employees e
3WHERE e.salary = (SELECT MAX(salary) FROM employees i WHERE i.department = e.department);
Result
namedepartmentsalary
CynthiaEngineering91000
ElenaSales58000
DavidMarketing47000

For each employee the inner query finds their department’s top salary and compares. Cynthia (91,000) tops Engineering — Alice (85,000) and Farid (73,000) do not match their department’s max. Elena (58,000) tops Sales and David (47,000) tops Marketing, so exactly the three department toppers come back.

--variants

Top earner per department

Each row compared to its own group’s maximum.

query.sql
1SELECT e.name, e.department, e.salary
2FROM employees e
3WHERE e.salary = (SELECT MAX(salary) FROM employees i WHERE i.department = e.department);
Result
namedepartmentsalary
CynthiaEngineering91000
ElenaSales58000
DavidMarketing47000
1Engineering’s max is 91,000 — only Cynthia matches; Alice (85k) and Farid (73k) don’t.
2Sales peaks with Elena (58k), Marketing with David (47k).
3Exactly one row per group — a GROUP BY would show the max, but not WHO earns it.

Above own department’s average

The group of reference is per-row, not global.

query.sql
1SELECT e.name, e.department, e.salary
2FROM employees e
3WHERE e.salary > (SELECT AVG(salary) FROM employees i WHERE i.department = e.department);
Result
namedepartmentsalary
AliceEngineering85000
CynthiaEngineering91000
ElenaSales58000
1Engineering avg = 83,000: Alice (85k) and Cynthia (91k) pass; Farid (73k) fails.
2Sales avg = 55,000: Elena passes, Bob (52k) fails. Marketing avg = 47,000: David exactly equals it, and > excludes equals.
3Result: Alice, Cynthia, Elena — each measured against their own department, not the company.

Correlated EXISTS — same power, different shape

Many correlated subqueries are existence tests in disguise.

query.sql
1SELECT e.name
2FROM employees e
3WHERE EXISTS (SELECT 1 FROM audit a WHERE a.employee_id = e.id AND a.action = 'raise');
4-- every employee who has ever had a raise logged
Result
name
Cynthia
1The probe references e.id — correlated — but only asks “is there one?”.
2EXISTS needs no aggregation, so it short-circuits on the first matching audit row.
3Prefer this over COUNT(*) > 0 — same answer, far less work.

The JOIN rewrite — same answer, one pass

Per-row subqueries become per-group joins.

query.sql
1WITH dept_max AS (
2 SELECT department, MAX(salary) AS max_sal
3 FROM employees GROUP BY department
4)
5SELECT e.name, e.department, e.salary
6FROM employees e
7JOIN dept_max dm ON e.department = dm.department AND e.salary = dm.max_sal;
Result
namedepartmentsalary
CynthiaEngineering91000
ElenaSales58000
DavidMarketing47000
1The CTE computes each department’s max once — not once per row.
2One hash join matches employees to their group’s max.
3Identical rows to the correlated version; on large tables this is dramatically cheaper.
--key facts
Runs per rowconceptually once per outer row — that N×M cost is the classic slow query
Decorrelationgood optimisers rewrite it as a join; EXPLAIN shows whether yours did
When it shinesper-group comparisons that are awkward to express as GROUP BY
--use cases
Per-group comparisons that GROUP BY cannot express (who IS the max, not what)
Existence checks per row (with EXISTS) in report filters
Latest-record-per-entity queries guarded with MAX()
Interview staple: know both the correlated and the JOIN/window rewrite
--under the hood
Naive planners re-execute the inner query per outer row — the plan shows a SubPlan node and the cost is O(N×M).
PostgreSQL and others decorrelate many forms automatically; if yours does not, the CTE + JOIN rewrite in the last case is the manual fix.

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.