Subqueries & CTEs
Nest one query in another, or name a step with WITH, to split a complex question into readable pieces.
What is it?
Some questions need more than one flat query. "Find users with more than 3 orders" needs a middle step: find the user ids with more than 3 orders, then look up those users.
- A subquery is a query nested inside another, in a WHERE, FROM, or SELECT clause. - A CTE (Common Table Expression), written with WITH, does the same but names the middle step so you can use it like a temporary table. This often makes multi-step queries much easier to read.
Explain like I'm 10
A subquery is scratch work in the margin before answering the real question. A CTE is the same scratch work with a clear label ('Step 1: frequent buyers'), so later readers, including future you, don't have to unpick a nested block.
Examples
A subquery in WHERE
SELECT name FROM users
WHERE id IN (
SELECT user_id FROM orders
GROUP BY user_id
HAVING COUNT(*) > 3
);The inner query finds every user_id with more than 3 orders. The outer query then finds the users with those ids.
The same query, using a CTE
WITH frequent_buyers AS (
SELECT user_id FROM orders
GROUP BY user_id
HAVING COUNT(*) > 3
)
SELECT users.name
FROM users
JOIN frequent_buyers ON frequent_buyers.user_id = users.id;WITH names the middle result frequent_buyers, and the rest of the query joins against it like a real table. Often easier to follow than a nested subquery once there's more than one step.
How it works
Conceptually, the database runs the inner subquery (or each CTE) first to get a middle result, then runs the outer query against it.
Postgres treats a CTE mostly as a named, temporary result you can select from or join. For hierarchical data (like a tree of comment replies), it also supports WITH RECURSIVE, which repeats a query against its own previous results until nothing new is found.
Why does it exist?
Many real questions ("customers who bought X but never Y," "the best-selling product in each category") can't be one flat SELECT. Subqueries and CTEs let you build the answer in stages inside one query, without extra round trips or hand-managed temporary tables.
When to use it
Use a CTE when a query has several logical steps and naming them makes it easier to read. Use an inline subquery for a small, self-contained filter that doesn't need a name.
When not to use it
If a plain JOIN or simple aggregation already answers the question, a subquery or CTE just adds indirection. Subqueries nested several levels deep get hard to read and optimize; pull a level out into a named CTE or rethink the query.
Common mistakes
Writing a correlated subquery (one that uses a column from the outer query) that effectively reruns once per outer row, which is very slow on large tables.
Assuming a CTE is always computed once and cached. This differs across databases and versions, so it isn't a guaranteed free optimization.
Nesting several layers of subqueries instead of naming steps with CTEs, making the query hard for others (or future you) to follow.
Practice exercises
- Easy:
Rewrite a subquery that uses = into one that uses IN, to find orders placed by a customer looked up by email.
- Medium:
Write a CTE that computes the average order total, then select all orders above that average.
- Hard:
Explain the difference between a correlated and a non-correlated subquery, with an example of each, and why the correlated one is usually slower.
Interview questions
What is a CTE and why use one instead of a plain subquery?
A WITH clause that names a middle query result. It mainly makes multi-step queries easier to read by labeling each stage instead of nesting subqueries.
What is a correlated subquery?
A subquery that uses a column from its outer query, so it conceptually reruns once per outer row.
Can a single query define more than one CTE?
Yes. List several CTEs in one WITH clause, separated by commas; later ones can reference earlier ones.