Skip to content
Commitwise
Menu

Correlated subquery

A subquery that refers to a column of the outer query, so it is evaluated once per outer row.

Definition

Easy to read ("for each customer, count their orders"), but on large results it can mean one lookup per row. Databases turn EXISTS and IN subqueries into joins automatically; scalar subqueries in the SELECT list often stay per-row, and rewriting them as a join to a grouped result does the work in one pass.

In practice

SELECT name, (SELECT count(*) FROM orders o WHERE o.customer_id = c.id) FROM customers c

Learn it in context

Lessons that use this term.

Related terms

Esc

Type to search the whole site.