SteelReed

Search

Search posts, questions…

SQL & Query TuningQuestion 9 / 37

Junior

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.

plain subquerycorrelatedOuter queryRuns onceindependentlyUses outer columnslogically per rowPlanner oftenflattens into a join

3 points to say:

  1. A subquery is a nested SELECT; four kinds by result: scalar, row, column, table.
  2. Correlated uses outer columns and logically reruns for every outer row.
  3. 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.