Common table expressions

Topic 4 of 4 in Combining queries10 min readBeginnerFree course

Overview

As questions get more involved, queries with subqueries inside subqueries become hard to read — you have to start in the middle and work outwards. A common table expression (CTE), written with WITH, lets you give each step a name and write the steps top to bottom, like a recipe. It’s probably the single biggest readability improvement you can make to complex SQL, and professional analysts use CTEs constantly.

Your first CTE

In Subqueries you calculated the average order value with a derived table. Here’s the same thing as a CTE:

SQL
WITH order_totals AS (
    SELECT order_id, sum(quantity * unit_price) AS total
    FROM order_items
    GROUP BY order_id
)
SELECT count(*)             AS orders,
       round(avg(total), 2) AS avg_order_value,
       max(total)           AS biggest_order
FROM order_totals;
Text
 orders | avg_order_value | biggest_order 
--------+-----------------+---------------
     24 |           50.58 |        113.00
(1 row)

WITH order_totals AS ( … ) defines a temporary named result. The main SELECT after it reads from order_totals exactly as if it were a table. The CTE exists only for the duration of this one statement.

The query does the same as the derived-table version, but it reads in the order you’d explain it: first compute each order’s total, then summarise.

Chaining CTEs

The real power appears with several steps. Separate CTEs with commas; each one can use the CTEs defined before it:

Common table expressions. WITH order_totals AS (SELECT order_id, sum(quantity * unit_price) AS total FROM order_items GROUP BY order_id), big_orders AS (SELECT * FROM order_totals WHERE total > 70) SELECT count(*) FROM big_orders. The data flows through a pipeline: order_items (raw rows) → order_totals (one row per order) → big_orders (filtered) → the final SELECT (the answer). WITH RECURSIVE is a query that refers to itself, for example walking a management chain: WITH RECURSIVE chain AS (SELECT id, name, manager_id, 1 AS level FROM employees WHERE manager_id IS NULL UNION ALL SELECT e.id, e.name, e.manager_id, c.level + 1 FROM employees e JOIN chain c ON e.manager_id = c.id). Each CTE is a named, temporary result that later parts of the query can use — like variables for queries.

SQL
WITH order_totals AS (
    SELECT order_id, sum(quantity * unit_price) AS total
    FROM order_items
    GROUP BY order_id
),
big_orders AS (
    SELECT * FROM order_totals WHERE total > 70
)
SELECT count(*) AS big_orders, sum(total) AS their_value
FROM big_orders;
Text
 big_orders | their_value 
------------+-------------
          6 |      533.05
(1 row)

A pipeline like this is easy to debug: replace the final SELECT with SELECT * FROM order_totals to check the first step, then SELECT * FROM big_orders to check the second.

A realistic report

Monthly revenue, counting only orders that weren’t cancelled, with the share of the year’s total:

SQL
WITH valid_orders AS (
    SELECT id, ordered_at
    FROM orders
    WHERE status <> 'cancelled'
),
order_totals AS (
    SELECT oi.order_id, sum(oi.quantity * oi.unit_price) AS total
    FROM order_items AS oi
    GROUP BY oi.order_id
),
monthly AS (
    SELECT date_trunc('month', v.ordered_at)::date AS month,
           count(*)     AS orders,
           sum(t.total) AS revenue
    FROM valid_orders AS v
    JOIN order_totals AS t ON t.order_id = v.id
    GROUP BY 1
)
SELECT month, orders, revenue,
       round(100 * revenue / (SELECT sum(revenue) FROM monthly), 1) AS pct_of_year
FROM monthly
ORDER BY month;
Text
   month    | orders | revenue | pct_of_year 
------------+--------+---------+-------------
 2026-01-01 |      3 |  169.50 |        14.8
 2026-02-01 |      2 |  117.75 |        10.3
 2026-03-01 |      3 |  145.65 |        12.7
 2026-04-01 |      2 |  100.25 |         8.7
 2026-05-01 |      2 |  120.00 |        10.5
 2026-06-01 |      1 |   27.25 |         2.4
 2026-07-01 |      1 |   77.50 |         6.8
 2026-08-01 |      1 |   40.50 |         3.5
 2026-09-01 |      2 |   97.40 |         8.5
 2026-10-01 |      2 |  147.50 |        12.9
 2026-11-01 |      3 |  102.75 |         9.0
(11 rows)

Each step has one job and a name that says what it is. Notice that monthly is used twice in the final query — once in FROM and once in the scalar subquery for the year’s total. A CTE can be referenced as many times as you like, which avoids repeating the same subquery.

CTE or subquery?

They’re largely interchangeable. Prefer a CTE when:

  • the query has more than one step, especially with aggregates on aggregates;
  • the same intermediate result is used more than once;
  • you want to test the steps separately.

A short, one-off filter like WHERE id IN (SELECT …) is fine as a subquery.

What about speed? Since PostgreSQL 12, a CTE that’s referenced once is usually folded into the main query and optimised together with it, so it costs nothing. A CTE referenced several times is computed once and reused. You can force either behaviour with WITH name AS MATERIALIZED (…) or AS NOT MATERIALIZED, but you’ll rarely need to.

Recursive CTEs

Some data is a tree: employees and managers, categories and sub-categories, comments and replies. In Self-joins and cross joins you climbed one level per join. A recursive CTE climbs (or descends) any number of levels.

It has two parts joined by UNION ALL:

  1. the anchor — the starting rows;
  2. the recursive part — a query that refers to the CTE itself, finding the next level from the rows found so far.

PostgreSQL runs the anchor, then runs the recursive part repeatedly on the newest rows until it returns nothing. Here’s the whole organisation chart, starting from the CEO:

SQL
WITH RECURSIVE chain AS (
    -- anchor: the top of the tree
    SELECT id, name, title, manager_id, 1 AS level,
           name::text AS path
    FROM employees
    WHERE manager_id IS NULL

    UNION ALL

    -- recursive part: everyone who reports to someone already found
    SELECT e.id, e.name, e.title, e.manager_id, c.level + 1,
           c.path || ' > ' || e.name
    FROM employees AS e
    JOIN chain AS c ON e.manager_id = c.id
)
SELECT repeat('    ', level - 1) || name AS org_chart, title, level
FROM chain
ORDER BY path;
Text
       org_chart       |       title        | level 
-----------------------+--------------------+-------
 Maya Singh            | CEO                |     1
     Lina Costa        | Head of Marketing  |     2
         Omar Haddad   | Marketing Analyst  |     3
     Tom Hughes        | Head of Operations |     2
         Raj Mehta     | Warehouse Lead     |     3
             Nina Berg | Packer             |     4
         Sofia Rossi   | Support Agent      |     3
(7 rows)

Round 1 found Maya; round 2 found her reports (Tom and Lina); round 3 their reports; round 4 Nina; round 5 found nobody, so it stopped. The path column builds the chain of names as it goes, which also gives a handy sort order for the chart.

Going the other way — from one person up to the top — just swaps the join direction:

SQL
WITH RECURSIVE bosses AS (
    SELECT id, name, manager_id, 1 AS level
    FROM employees
    WHERE name = 'Nina Berg'
    UNION ALL
    SELECT m.id, m.name, m.manager_id, b.level + 1
    FROM employees AS m
    JOIN bosses AS b ON m.id = b.manager_id
)
SELECT string_agg(name, ' → ' ORDER BY level) AS reporting_line
FROM bosses;
Text
                 reporting_line                  
-------------------------------------------------
 Nina Berg → Raj Mehta → Tom Hughes → Maya Singh
(1 row)

Infinite loops: if the data contains a cycle (A manages B, B manages A), a recursive CTE would run forever. Guard against it with a level limit (WHERE c.level < 20 in the recursive part) or PostgreSQL’s CYCLE clause.

Recursive CTEs can also generate sequences — though for dates and numbers, generate_series is simpler:

SQL
WITH RECURSIVE days(day) AS (
    SELECT date '2026-12-01'
    UNION ALL
    SELECT day + 1 FROM days WHERE day < date '2026-12-05'
)
SELECT day, to_char(day, 'FMDay') AS weekday FROM days ORDER BY day;
Text
    day     |  weekday  
------------+-----------
 2026-12-01 | Tuesday
 2026-12-02 | Wednesday
 2026-12-03 | Thursday
 2026-12-04 | Friday
 2026-12-05 | Saturday
(5 rows)

Other databases: WITH is standard and supported by every major database, including MySQL 8 and SQLite. Most require the RECURSIVE keyword for recursive CTEs, as PostgreSQL does; SQL Server and Oracle leave it out.

Exercise

Our biggest spenders

Write a query with two CTEs. The first, order_totals, has one row per order: order_id and total (the sum of quantity × unit price from order_items). The second, customer_totals, joins orders to order_totals, ignores cancelled orders, and gives each customer_id its number of orders and the amount spent. The final SELECT joins customer_totals to customers and returns first_name, orders and spent for customers who spent more than 130, biggest spender first. You should get Ben, Asha, Grace and Elena.

SQL
WITH order_totals AS (
  SELECT order_id, sum(quantity * unit_price) AS total
  FROM order_items
  GROUP BY order_id
)
SELECT * FROM order_totals;

Summary

  • WITH name AS (query) defines a common table expression: a named, temporary result that the rest of the query can use like a table.
  • Several CTEs can be chained, separated by commas, each able to use the ones before it.
  • CTEs turn nested subqueries into top-to-bottom steps that are easy to read, test and change.
  • A CTE can be referenced more than once in the main query.
  • WITH RECURSIVE lets a CTE refer to itself, which walks trees and hierarchies of any depth.