# Topic 34: Correlated Subqueries
Outer query row dependencies, execution overhead, decorrelation optimizations, and window function alternatives.
1. Definition
A correlated subquery is a nested query that depends on column values from the outer query for its evaluation, executing conceptually once for each candidate row processed by the outer query.
2. Explain Like I'm 5
An uncorrelated subquery is like looking up the weather once for everyone. A correlated subquery is like calling every person individually to ask what clothes they are wearing based on their specific city.
3. Animation & Visual Simulation
Interactive Engine TraceCorrelated Subqueries Visual Simulator
SELECT o1.id, o1.customer_id, o1.amount
FROM orders o1
WHERE o1.amount = (
SELECT MAX(o2.amount) FROM orders o2 WHERE o2.customer_id = o1.customer_id
);Active InputStep 1: Input & Parsing Stage
Initiating Correlated Subqueries
Checking Table Invariants
The database engine inspects active tables, verifies permissions, and prepares the physical operation.
4. Real-World Example
Finding employees who earn more than the average salary of their own specific department.
| id | dept | salary | Dept Avg |
|---|---|---|---|
| 1 | Eng | $130,000 | $110,000 (Matched) |
| 2 | Eng | $90,000 | $110,000 (Filtered) |
| 3 | HR | $85,000 | $75,000 (Matched) |
5. SQL Syntax
ANSI SQL / PostgreSQL DialectSELECT e1.name, e1.department, e1.salary FROM employees e1 WHERE e1.salary > ( SELECT AVG(e2.salary) FROM employees e2 WHERE e2.department = e1.department -- Outer reference! );
WITH ranked AS (
SELECT name, department, salary,
AVG(salary) OVER (PARTITION BY department) AS dept_avg
FROM employees
)
SELECT name, department, salary
FROM ranked
WHERE salary > dept_avg;6. Important Rules & Behaviors
| Rule | Behavioral Explanation |
|---|---|
| Outer Scope Dependency | Correlated subqueries cannot execute independently in isolation because they require outer values. |
| N+1 Execution Penalty | Without optimizer decorrelation, evaluating a correlated subquery on N outer rows can cause O(N^2) complexity. |
| Decorrelation | Advanced database optimizers rewrite correlated subqueries into hash or merge joins. |
| Outer row dependency | Correlated subqueries reference columns from the enclosing outer query, binding them to outer execution loops. |
| Quadratic complexity risk | If un-optimized, a correlated subquery executes M times for N outer rows, scaling as O(N * M). |
7. Deep Dive: Correlated Subqueries vs Window Functions Performance
On a table of 100,000 rows, a naive correlated subquery could theoretically execute the inner query 100,000 times! Using an analytic window function (AVG(salary) OVER (PARTITION BY dept)) accomplishes the same result in a single O(N log N) scan.
-- Naive correlated subquery (potentially slow): WHERE salary > (SELECT AVG(salary) FROM emp e2 WHERE e2.dept = e1.dept) -- High performance window function (1 pass): SELECT * FROM ( SELECT *, AVG(salary) OVER (PARTITION BY dept) AS d_avg FROM emp ) t WHERE salary > d_avg;
8. Advantages & Disadvantages
Advantages
- •Expressive and intuitive for per-entity comparisons.
- •Works seamlessly in UPDATE and DELETE statements to target rows based on child tables.
Disadvantages & Trade-offs
- •Can cause devastating O(N^2) query slowdowns if the engine fails to decorrelate.
9. Common Interview Questions
Q1.What is a Correlated Subquery and why is it often a major performance bottleneck?
A Correlated Subquery is an inner query that references a column from the outer query (e.g. WHERE salary > (SELECT AVG(salary) FROM employees e2 WHERE e2.department_id = e1.department_id)). If the Cost-Based Optimizer cannot unnest the query, the engine is forced to execute the subquery once for EVERY SINGLE ROW in the outer table, resulting in O(N * M) nested-loop execution that brings large databases to a crawl.
Q2.How do you rewrite a correlated subquery into a Window Function for 100x faster performance?
Instead of computing the department average row-by-row in an inner subquery, you compute it in a single pass using an analytical window function: WITH dept_avg AS (SELECT id, name, department_id, salary, AVG(salary) OVER (PARTITION BY department_id) AS avg_sal FROM employees) SELECT * FROM dept_avg WHERE salary > avg_sal; This executes in a single streaming pass in O(N log N) time.
Q3.Can the query optimizer automatically decorrelate a subquery into a JOIN?
Yes! Modern optimizers (PostgreSQL, Oracle, SQL Server) recognize correlated subqueries matching Semi-Join or Anti-Join patterns (such as WHERE EXISTS (SELECT 1 FROM ... WHERE outer.id = inner.id)) and automatically transform them into physical Hash Semi-Joins or Merge Semi-Joins, eliminating the nested loop.
Q4.What is the difference between an Uncorrelated Subquery and a Correlated Subquery?
An Uncorrelated Subquery has no dependencies on the outer query: it can be executed once at the start of the query, its result cached in memory, and reused for all outer rows. A Correlated Subquery depends directly on values from the current outer row, meaning its result changes dynamically as the outer scan progresses.
Q5.How do you find the highest-paid employee per department using a correlated subquery vs CTE?
Using correlated subquery: SELECT * FROM employees e WHERE salary = (SELECT MAX(salary) FROM employees e2 WHERE e2.dept_id = e.dept_id); Using CTE with window function: WITH ranked AS (SELECT *, DENSE_RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) AS rnk FROM employees) SELECT * FROM ranked WHERE rnk = 1; The CTE approach avoids repeated table scans and handles ties cleanly.
10. Interview-Ready Answer
“A correlated subquery references values from the outer query, evaluating dynamically per candidate row. While powerful for per-group filtering, window functions or join transformations are generally preferred to avoid row-by-row execution penalties.”
11. Quick Test
Why can a correlated subquery NOT be tested by running its inner query independently in a database GUI?