Skip to content

CTEs and subqueries

Split a hard question into named steps with CTEs, and know when a subquery is the simpler tool.

Practise: 14 questions

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:

  1. Write down the steps in words first. "One row per customer with total spend. Average of those totals. Customers above it."
  2. Make each step a CTE with a name that says what one row is: customer_spend, not t1.
  3. Check each CTE alone by selecting from it. Fix it before building on it.
  4. 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

Variations

In other warehouses

Practise ctes and subqueries