What is a subquery, and what kinds are there? How does a correlated subquery differ from a regular one?
Short answer
A subquery is a SELECT nested inside another SQL statement; by result shape there are four kinds: scalar, row, column, table. A correlated subquery references a column of the outer query, so logically it reruns for each outer row; a plain subquery runs independently.
3 points to say:
- A subquery is a nested
SELECT; four kinds by result: scalar, row, column, table. - Correlated uses outer columns and logically reruns for every outer row.
- The planner often flattens it into a join; alternatives are window functions or
LATERAL.
Keep reading the deep dive
Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.