Subqueries and CTEs

A subquery is a query used as a value, a table, or a test. A CTE is the same thing with a name. Most of what makes this topic confusing is that the four positions behave differently, so this lesson is organised by position.

Position 1: as a single value (scalar)

SELECT name, salary,
       salary - (SELECT avg(salary) FROM employee) AS vs_average
FROM employee
ORDER BY vs_average DESC;

The subquery returns exactly one row and one column, so it can be used wherever a number can. If it returns more than one row you get an error at runtime rather than at parse time:

SELECT name, (SELECT id FROM department) AS d FROM employee;
ERROR:  more than one row returned by a subquery used as an expression

That is a failure mode worth respecting: a scalar subquery that is correct today becomes a runtime error when the data grows a second matching row. Add a LIMIT 1 only if “any one of them” is genuinely what you mean — usually it is not, and the right fix is a JOIN or an aggregate.

Position 2: as a set, with IN / EXISTS

SELECT name
FROM employee
WHERE department_id IN (SELECT id FROM department WHERE building = 'Riverside')
ORDER BY name;

EXISTS asks the same kind of question but about rows rather than values, and is the form that survives nulls:

SELECT d.name
FROM department d
WHERE EXISTS (SELECT 1 FROM employee e WHERE e.department_id = d.id)
ORDER BY d.name;

SELECT 1 rather than SELECT * is a convention, not an optimisation — the engine does not evaluate the select list of an EXISTS either way. It reads as “I only care whether a row exists”, which is the point.

For why NOT IN is the one to avoid here, see NULLs in joins and filters.

Position 3: as a table (derived table)

SELECT d.name AS department, t.headcount
FROM (
  SELECT department_id, count(*) AS headcount
  FROM employee
  GROUP BY department_id
) t
JOIN department d ON d.id = t.department_id
ORDER BY t.headcount DESC, d.name;

This is the shape that fixes fan-out: aggregate to one row per key first, then join. It is the same query from the grain lesson, and it is the most important subquery position in practice.

A derived table must be aliased — t here — and that alias is how you reference its columns.

Position 4: correlated — referencing the outer row

SELECT e.name, e.salary
FROM employee e
WHERE e.salary = (
  SELECT max(s.salary) FROM employee s WHERE s.department_id = e.department_id
)
ORDER BY e.name;

The inner query mentions e.department_id, so it cannot be evaluated once — it depends on which outer row is being considered. Conceptually it runs per row.

In practice the planner usually rewrites it. Postgres will often turn a correlated subquery into a hash aggregate plus a join, which is why “correlated subqueries are slow” is folklore rather than a rule. What is true is that it can degrade into a per-row loop when the planner cannot rewrite it — typically when the correlation involves a function call or a non-equality condition — and when it does, the cost is the inner query’s cost multiplied by the outer row count.

The way to know is to look, which is what reading a query plan is for. A SubPlan with a high loops count is the signature.

WITH — the same thing with a name

WITH dept_headcount AS (
  SELECT department_id, count(*) AS headcount
  FROM employee
  GROUP BY department_id
),
dept_revenue AS (
  SELECT e.department_id, coalesce(sum(s.amount), 0) AS revenue
  FROM employee e
  LEFT JOIN sale s ON s.employee_id = e.id
  GROUP BY e.department_id
)
SELECT d.name AS department, h.headcount, r.revenue
FROM department d
JOIN dept_headcount h ON h.department_id = d.id
JOIN dept_revenue r ON r.department_id = d.id
ORDER BY r.revenue DESC, d.name;

Two independent aggregations, each at its own grain, joined once. Written as nested derived tables this is the same query and considerably harder to read, because the reader has to work inside-out.

A CTE is the right default for anything with two or more steps. It reads top to bottom, each step has a name you can say out loud, and a name can be reused in two places without being written twice.

The optimisation-fence change

For years the advice was “a CTE in Postgres is an optimisation fence” — it was always materialised, so predicates could not be pushed into it, and a CTE could be dramatically slower than the equivalent derived table.

That changed in Postgres 12. A CTE referenced once and without side effects is now inlined like a derived table. You can still force either behaviour:

WITH recent AS MATERIALIZED (
  SELECT * FROM sale WHERE closed_on >= '2024-02-01'
)
SELECT count(*) FROM recent;

MATERIALIZED forces the old behaviour, NOT MATERIALIZED forces inlining. Reach for MATERIALIZED when a CTE is expensive and referenced several times and you want it computed once; otherwise leave it alone.

This is the kind of fact worth dating in an interview. “It was a fence before 12 and is inlined now” is a better answer than either half on its own.

Try it

Run the two-CTE query in the SQL playground and then rewrite it with nested derived tables. The result is identical and the second version is the one you would not want to maintain.

Drill it with Revenue and headcount per department.

Interview questions

1. What is a correlated subquery, and is it always slow? One that references a column from the outer query, so it conceptually runs per outer row. Not always slow — Postgres often rewrites it into a join plus aggregate. It degrades when the planner cannot rewrite it, which a plan with a high loops count on a SubPlan reveals.

2. When does a scalar subquery fail? At runtime, if it returns more than one row. A query that is correct against today’s data can start failing when a second matching row appears.

3. Why is a derived table the fix for join fan-out? Because aggregating to one row per key before joining makes the join one-to-one, so nothing multiplies and aggregates over the other side are counted once.

4. Is a CTE in Postgres an optimisation fence? It was before version 12. Since 12, a CTE referenced once and free of side effects is inlined; MATERIALIZED and NOT MATERIALIZED force either behaviour explicitly.

5. When would you deliberately write MATERIALIZED? When a CTE is expensive and referenced several times, so computing it once and reusing it beats inlining it into each reference.

6. EXISTS or IN — does it matter which you pick? For correctness it matters in the negative form: NOT IN breaks against a nullable column and NOT EXISTS does not. For performance they usually plan the same in Postgres, so prefer the one that states the question.

Next

Window functions for backend interviews — ranking without collapsing the rows.