When you need it
You need steps when the answer depends on an intermediate result: "customers whose spend is above the average customer", "the share of each product in its category total", "orders larger than that customer's own average". Words that signal it: "than the average", "compared with", "of those", "then".
Interviewers watch how you structure the query as much as the result. A readable chain of CTEs beats one tangled select.
The shape of the query
with step_one as (
select ... from ... group by ...
),
step_two as (
select ... from step_one join ...
)
select ... from step_two;Step by step:
- Write down the steps in words first. "One row per customer with total spend. Average of those totals. Customers above it."
- Make each step a CTE with a name that says what one row is:
customer_spend, nott1. - Check each CTE alone by selecting from it. Fix it before building on it.
- Keep the final select short.
with customer_spend as (
select o.customer_id, sum(oi.quantity * oi.unit_price) as spend
from orders o
join order_items oi on oi.order_id = o.order_id
where o.status = 'completed'
group by o.customer_id
)
select customer_id, round(spend, 2) as spend
from customer_spend
where spend > (select avg(spend) from customer_spend)
order by spend desc, customer_id
limit 10;The scalar subquery (select avg(spend) ...) returns one value and is compared inline. Use it when you need a single number. Use a CTE or join when you need a column per row.
A correlated subquery refers to the outer row. This compares each employee with their own department:
select e.employee_id, e.full_name, e.salary
from employees e
where e.termination_date is null
and e.salary > (
select avg(x.salary)
from employees x
where x.department_id = e.department_id
and x.termination_date is null
)
order by e.salary desc, e.employee_id
limit 10;Traps interviewers look for
- A scalar subquery that returns more than one row. It errors, or worse, it is silently wrong on a different engine. Make sure it aggregates or is keyed.
NOT INwith NULLs. If the subquery returns a NULL,NOT INmatches nothing. PreferNOT EXISTS. See the lesson on rows with no match.- Repeating the same logic in two CTEs. If "completed orders" is defined twice, one will drift. Define it once and reuse it.
- Filtering at the wrong step. A filter applied before an aggregate changes what is aggregated. A filter after changes only what is shown. Say which one you mean.
- Correlated subqueries on big tables. They can run once per outer row. A join to a pre-aggregated CTE is usually faster and easier to read.
- Believing CTEs are always materialised. Some engines inline them, some compute them once. Do not rely on a CTE to freeze a result that depends on
random()or the clock.
Variations
- Derived table.
from (select ...) tdoes the same job as a CTE and is fine for a single step. - Chained CTEs. Later CTEs can read earlier ones, so a three-step plan is three names.
- Recursive CTE.
with recursivewalks a hierarchy or builds a series. Rare in screens, common for org charts. EXISTSandINsubqueries. Filter one table by membership in another without joining.- Subquery in
SELECT. Works for a per-row lookup but a join is almost always clearer.
In other warehouses
- Snowflake, BigQuery, Redshift, MySQL (8 and later) and Databricks support
WITH. SQL Server does too, but a CTE must be preceded by a statement ending in a semicolon. - Recursive CTEs: PostgreSQL, MySQL, Snowflake, BigQuery and Redshift write
with recursive. SQL Server writes justwith, with norecursivekeyword. - BigQuery and Snowflake let a CTE be referenced many times in one query with no special syntax.
- MySQL before version 8 has no CTEs, so you would need derived tables.