Selects inside selects
A subquery is a SELECT statement nested inside another statement. Three common shapes:
- Scalar subquery — returns one value, used as a column or in a comparison:
SELECT name, (SELECT count(*) FROM messages WHERE conversation_id = c.id) AS n FROM conversations c; - IN subquery — returns a set, used as the right-hand side of
IN. - EXISTS subquery — returns true/false:
WHERE EXISTS (SELECT 1 FROM messages m WHERE m.conversation_id = c.id). - Derived table — used in FROM:
FROM (SELECT brain, count(*) AS n FROM messages GROUP BY brain) AS sub WHERE sub.n > 100;
Tip: Many subqueries can be rewritten as joins or CTEs and sometimes the rewrite is faster. Use
EXPLAIN QUERY PLAN (covered in track 5) to compare. For deeply-nested logic, CTEs (track 8) usually read better than nested subqueries.