Correlated subqueries: reference an outer row
Overview
A correlated subquery references a column from an enclosing query. Its logical result depends on the current outer row, making it useful for per-customer summaries and related-record comparisons.
First example
SELECT c.id, (SELECT COUNT(*) FROM orders o WHERE o.customer_id = c.id) AS order_countFROM customers c ORDER BY c.id;Observed SQLite result (rows in JSON):
[ [ 1, 2 ], [ 2, 1 ], [ 3, 0 ]]How it works
For each customer c, the inner WHERE restricts orders to that customer. COUNT returns zero for Sara. The second query selects orders equal to the maximum order ID for their customer; IDs 102 and 103 qualify. An ID is used as a deterministic ranking key, not as evidence of actual time. Always qualify inner and outer columns with aliases: an unqualified reference may bind to the wrong scope. The logical dependency does not imply a particular physical loop; optimizers may transform the query. Compare execution plans on representative data before making performance claims.
Practical example
SELECT o.id, o.customer_id FROM orders oWHERE o.id = (SELECT MAX(i.id) FROM orders i WHERE i.customer_id = o.customer_id)ORDER BY o.id;Observed SQLite result (rows in JSON):
[ [ 102, 1 ], [ 103, 2 ]]Practice and mistakes
Practice: replace COUNT with MAX(o.id) in the customer summary and predict 102, 103, NULL. Compare the count query with a LEFT JOIN and GROUP BY. Explain why counting all joined rows would miscount Sara.