Skill 1.3.7

Write correlated queries

Key Concepts

EXISTS and NOT EXISTS with a correlated subquery test whether related rows exist, for example customers with no order in the last year; NOT EXISTS is safer than NOT IN, which returns no rows when the subquery yields a NULL. A correlated scalar subquery in the SELECT list returns one value per outer row, such as each product's latest price, and must return at most one row.

The optimizer usually rewrites correlated subqueries as joins (semi-joins for EXISTS), so they are not necessarily slow, but supporting indexes on the correlation columns matter. CROSS APPLY and OUTER APPLY are correlated table expressions that can return several columns and rows per outer row, such as the top three orders per customer, which a scalar subquery cannot.