Correlated Subqueries
A subquery that references the outer query's row.
Questions this answers
- →How do I find each customer's most recent order?
- →How do I get the top item per group?
- →How do I check if related rows exist?
How it works
A correlated subquery references a column from the outer query. It re-runs for every row in the outer query, which makes it powerful but potentially slow. EXISTS is a common pattern — it checks whether the subquery returns any rows at all.
EXISTS check
-- Customers who have placed at least one order SELECT name FROM customers c WHERE EXISTS ( SELECT 1 FROM orders o WHERE o.customer_id = c.id );
💡 EXISTS is faster than IN for large datasets — it stops as soon as it finds one match.
Find the max per group
-- Each artist's most-streamed song SELECT a.name, s.title, s.streams FROM songs s JOIN artists a ON s.artist_id = a.id WHERE s.streams = ( SELECT MAX(streams) FROM songs s2 WHERE s2.artist_id = s.artist_id );
Ready to practise Correlated Subqueries?
Solve real exercises with AI feedback — free to start.
Try it free →