Skip to the page

Querying · mid

Subqueries, EXISTS and CTEs (including recursive)

A subquery is a query inside another (scalar, IN/EXISTS, or a derived table); a correlated subquery runs per outer row; a CTE (WITH name AS (...)) names a subquery to make complex queries readable, and WITH RECURSIVE walks trees like categories or org charts.

The notes

What you must know

  • Scalar subquery: returns one value, e.g. WHERE salary > (SELECT AVG(salary) FROM emp).
  • IN (subquery) and EXISTS (subquery): EXISTS stops at the first match and is NULL-safe; NOT EXISTS is the safe anti-join.
  • Correlated subquery: references the outer row (WHERE o.user_id = u.id); conceptually runs once per row, though optimisers often turn it into a join.
  • CTE: WITH paid AS (SELECT ...) SELECT ... FROM paid. Several CTEs can chain. Since Postgres 12, simple CTEs are inlined (optimised like subqueries) unless MATERIALIZED is written.
  • Recursive CTE: anchor query UNION ALL a query that joins to the CTE itself; used for trees (category -> subcategory), comment threads, org charts. Guard against cycles.
  • Derived tables (subquery in FROM) and CTEs let you filter on window function results (you cannot use a window function in WHERE directly).

The red pen

Common traps: mistake → fix

  • Mistake: Subqueries are always slow

    Fix: modern planners rewrite many into joins; read the plan before rewriting.

  • Mistake: CTEs are always materialised (an optimisation fence)

    Fix: that was true in Postgres before 12; now simple CTEs are inlined.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is a correlated subquery? Give an example.
  2. IN vs EXISTS? NOT IN vs NOT EXISTS?
  3. Why use a CTE?
  4. How would you fetch a whole category tree, or all replies under a comment, in one query?

Practise

Practise with these questions

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview