01 / 21

Correlated
Subqueries

Learn how a subquery can reference the outer query to filter, compute, and compare data row by row: the most powerful pattern in SQL.

SQL

What Is a Subquery?

A subquery is a complete SELECT statement nested inside another SQL statement. It lives inside parentheses and can appear in the WHERE, SELECT, or FROM clause.

Inner Query
The nested SELECT that runs and produces a result set used by the outer query.
Outer Query
The main SELECT that consumes the inner query's result to filter or compute its own output.

Two Kinds of Subqueries

Non-Correlated
Runs once, independently of the outer query. The inner query doesn't reference outer columns.
Correlated
Runs once per outer row. The inner query references a column from the outer query, creating a dependency.

Why Do Correlated Subqueries Matter?

Many real-world questions require comparing each row against its own group: "Is this employee's salary above their department average?" A plain subquery can't answer that because the answer is different for every row.

Row-Level Filtering
Compare each row to a dynamically computed value that depends on that row's data.
EXISTS Checks
Test whether related rows exist in another table for each outer row.
Computed Columns
Add a per-row calculated value in the SELECT list without a JOIN.

Anatomy of a Correlated Subquery

SELECT e.name, e.salary FROM employees e WHERE e.salary > ( SELECT AVG(e2.salary) FROM employees e2 WHERE e2.dept_id = e.dept_id -- references outer "e" );

How the Database Executes It

Outer Query Row 1: Alice, Sales Row 2: Bob, Eng Row 3: Carol, Sales Row 4: Dave, Eng Inner Query (for Bob's row) SELECT AVG(salary) FROM employees e2 WHERE e2.dept_id = 'Eng' Returns AVG = 72000
\( \text{Bob.salary} > 72000? \)
If yes → include Bob Repeat for every outer row

The Core Rule

1
Outer alias required: the outer table must be aliased so the inner query can reference it unambiguously.
2
Inner references outer: a WHERE or ON clause in the inner query compares an inner column to an outer column.
3
Evaluated per row: conceptually, the inner query re-executes for every row of the outer query.

Non-Correlated vs Correlated

Non-Correlated Correlated
References outer query? No Yes
Execution count Once Once per outer row
Can run standalone? Yes No
Typical use Global filter or list Row-by-row comparison
Performance Generally faster Can be slower (optimizable)

Where Can They Appear?

In WHERE
Filter rows by comparing to a per-row computed value (most common usage).
In SELECT
Add a calculated column for each row, like a per-department count alongside each employee.
With EXISTS
Check if at least one matching row exists in a related table. Returns TRUE/FALSE per row.

How to Write a Correlated Subquery

1
Write the outer query first. Decide which table and columns you need, and alias the table.
2
Identify the per-row question. What value must be computed differently for each outer row?
3
Write the inner SELECT. Use a different alias for the inner table (even if it's the same table).
4
Add the correlation condition. In the inner WHERE, equate an inner column to an outer column using the outer alias.
5
Test and verify. Make sure the inner query would fail if you ran it alone (confirming the correlation).

Example 1: Above-Average Salary

Goal: find employees earning more than the average salary in their own department.

SELECT e.name, e.dept, e.salary FROM employees e WHERE e.salary > ( SELECT AVG(e2.salary) FROM employees e2 WHERE e2.dept = e.dept );

Example 2: EXISTS Check

Goal: find customers who have placed at least one order.

SELECT c.name FROM customers c WHERE EXISTS ( SELECT 1 FROM orders o WHERE o.customer_id = c.id );

Example 3: Computed Column

Goal: show each product alongside the total quantity ever ordered for that product.

SELECT p.name, p.price, (SELECT SUM(oi.qty) FROM order_items oi WHERE oi.product_id = p.id ) AS total_ordered FROM products p;

The NOT EXISTS Pattern

Goal: find customers who have never placed an order.

SELECT c.name FROM customers c WHERE NOT EXISTS ( SELECT 1 FROM orders o WHERE o.customer_id = c.id );

Common Mistakes

✕ Forgetting the Alias
Using the same alias (or no alias) for inner and outer tables causes ambiguous column references or incorrect results.
✕ Missing Correlation
Writing a subquery that doesn't reference the outer query: it runs once and applies the same value to every row.
✕ Returning Multiple Rows
Using a correlated subquery with \(=\) or \(>\) when it returns more than one row. Use IN, ANY, ALL, or ensure it returns a scalar.

Summary of Patterns

Pattern Clause Use Case
Scalar comparison WHERE col \(>\) (...) Above/below per-group aggregate
EXISTS WHERE EXISTS (...) Row has related records
NOT EXISTS WHERE NOT EXISTS (...) Row has no related records
Computed column SELECT (...) AS col Per-row aggregation in output
IN with correlation WHERE col IN (...) Row matches any value in a group

Question 1 of 5

What makes a subquery "correlated"?

Question 2 of 5

What does this query return?

Question 3 of 5

Which keyword is commonly used with a correlated subquery to check if related rows exist?

Question 4 of 5

If the outer query has 100 rows, how many times does a correlated subquery conceptually execute?

Question 5 of 5

What does this query return?