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.
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.
Two Kinds of Subqueries
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.
Anatomy of a Correlated Subquery
How the Database Executes It
The Core Rule
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?
How to Write a Correlated Subquery
Example 1: Above-Average Salary
Goal: find employees earning more than the average salary in their own department.
Example 2: EXISTS Check
Goal: find customers who have placed at least one order.
Example 3: Computed Column
Goal: show each product alongside the total quantity ever ordered for that product.
The NOT EXISTS Pattern
Goal: find customers who have never placed an order.
Common Mistakes
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?