Skip to content
Back to 50 Concepts
Topic 34 of 50query-executionAdvanced

# 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.

Relational Invariant:Deterministic relational algebra contract evaluated by the Cost-Based Optimizer.

2. Explain Like I'm 5

Intuitive mental model for beginners

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 Trace
Interactive Engine Simulation

Correlated Subqueries Visual Simulator

Step 1 of 3
SQL>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 Input

Step 1: Input & Parsing Stage

Engine Action: Validate SQL syntax and resolve schema metadata for Correlated Subqueries
SQL Input

Initiating Correlated Subqueries

Schema Catalog

Checking Table Invariants

How the Database Executes This:

The database engine inspects active tables, verifies permissions, and prepares the physical operation.

💡 Teacher grading on a curve: For every student, the teacher looks at that specific student's section, calculates that section's score, and compares.

4. Real-World Example

Finding employees who earn more than the average salary of their own specific department.

Employees
iddeptsalaryDept Avg
1Eng$130,000$110,000 (Matched)
2Eng$90,000$110,000 (Filtered)
3HR$85,000$75,000 (Matched)
Relational walkthrough: The inner query computes the average for e1.dept, tying it to the outer row.

5. SQL Syntax

ANSI SQL / PostgreSQL Dialect
Step 1: Correlated subquery with outer reference
SELECT 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!
);
e1 is referenced inside the subquery.
Step 2: Optimized alternative using Window Functions
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;
Executes in a single sorted pass instead of row-by-row.

6. Important Rules & Behaviors

RuleBehavioral Explanation
Outer Scope DependencyCorrelated subqueries cannot execute independently in isolation because they require outer values.
N+1 Execution PenaltyWithout optimizer decorrelation, evaluating a correlated subquery on N outer rows can cause O(N^2) complexity.
DecorrelationAdvanced database optimizers rewrite correlated subqueries into hash or merge joins.
Outer row dependencyCorrelated subqueries reference columns from the enclosing outer query, binding them to outer execution loops.
Quadratic complexity riskIf 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;
Caution: Always check EXPLAIN plans for correlated subqueries to ensure the engine successfully decorrelated them.

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

Scenario Question:

Why can a correlated subquery NOT be tested by running its inner query independently in a database GUI?

Select your answer: