TExcelTAD
Home › SQL › SQL Common Table Expressions

SQL Common Table Expressions

A common table expression (CTE) gives a subquery a name at the start of a statement with WITH. The main query can then use that name like a table. CTEs make long queries readable from top to bottom, and recursive CTEs can walk hierarchies such as an org chart.

sql
WITH name AS (
  SELECT …
)
SELECT … FROM name …;

A first CTE

Order totals, then the orders above average:

sql · try it yourself
WITH order_totals AS (
  SELECT oi.order_id, ROUND(SUM(oi.quantity * p.price), 2) AS total
  FROM order_items AS oi
  JOIN products AS p ON p.product_id = oi.product_id
  GROUP BY oi.order_id
)
SELECT order_id, total
FROM order_totals
WHERE total > (SELECT AVG(total) FROM order_totals)
ORDER BY total DESC
LIMIT 6;
order_id | total
---------+-------
31       | 489.5
14       | 447
13       | 267
19       | 263.95
27       | 251.3
10       | 248.96
(6 rows)

Notice that order_totals is used twice — once in FROM, once in the subquery — but written only once.

Several CTEs

Separate CTEs with commas; later ones may use earlier ones. Revenue per customer, then each customer's share of the total:

sql · try it yourself
WITH lines AS (
  SELECT o.customer_id, oi.quantity * p.price AS amount
  FROM orders AS o
  JOIN order_items AS oi ON oi.order_id = o.order_id
  JOIN products AS p ON p.product_id = oi.product_id
  WHERE o.status <> 'cancelled'
),
per_customer AS (
  SELECT customer_id, SUM(amount) AS revenue
  FROM lines
  GROUP BY customer_id
),
grand AS (
  SELECT SUM(revenue) AS total FROM per_customer
)
SELECT c.name,
       ROUND(pc.revenue, 2) AS revenue,
       ROUND(100.0 * pc.revenue / g.total, 1) AS pct
FROM per_customer AS pc
JOIN customers AS c ON c.customer_id = pc.customer_id
CROSS JOIN grand AS g
ORDER BY pc.revenue DESC
LIMIT 5;
name         | revenue | pct
-------------+---------+-----
Green Fork   | 660.2   | 15.6
Bright Bytes | 655.13  | 15.5
Amara Costa  | 593.35  | 14
Felix Reyes  | 450.45  | 10.6
Kai Moreau   | 362.33  | 8.6
(5 rows)

Read it like a recipe: first the lines, then per customer, then the grand total, then the final result.

Recursive CTEs

A recursive CTE refers to itself. It has two parts joined by UNION ALL:

  1. the anchor query, which produces the starting rows;
  2. the recursive query, which joins the CTE to produce the next level — and stops when it produces no rows.

The simplest example counts from 1 to 5:

sql · try it yourself
WITH RECURSIVE counter(n) AS (
  SELECT 1                              -- anchor
  UNION ALL
  SELECT n + 1 FROM counter WHERE n < 5 -- recursive step
)
SELECT n FROM counter;
n
-
1
2
3
4
5
(5 rows)

Walking the employee hierarchy

Start with the CEO (no manager), then repeatedly add the people who report to someone already found. Track the level and the path:

sql · try it yourself
WITH RECURSIVE org AS (
  SELECT employee_id, first_name, title, 0 AS level,
         first_name AS path
  FROM employees
  WHERE manager_id IS NULL

  UNION ALL

  SELECT e.employee_id, e.first_name, e.title, org.level + 1,
         org.path || ' > ' || e.first_name
  FROM employees AS e
  JOIN org ON e.manager_id = org.employee_id
)
SELECT substr('        ', 1, level * 4) || first_name AS employee, title, level, path
FROM org
ORDER BY path;
employee      | title              | level | path
--------------+--------------------+-------+-----------------------
Grace         | CEO                | 0     | Grace
    Elena     | Data Analyst       | 1     | Grace > Elena
    Lin       | Operations Manager | 1     | Grace > Lin
        Hana  | Support Specialist | 2     | Grace > Lin > Hana
        Marco | Warehouse Lead     | 2     | Grace > Lin > Marco
    Victor    | Sales Manager      | 1     | Grace > Victor
        Aisha | Sales Rep          | 2     | Grace > Victor > Aisha
        Owen  | Sales Rep          | 2     | Grace > Victor > Owen
        Rosa  | Sales Rep          | 2     | Grace > Victor > Rosa
        Tom   | Sales Rep          | 2     | Grace > Victor > Tom
(10 rows)

The same pattern answers "who are all the people under Victor, directly or indirectly?" — just start the anchor at employee_id = 2.

Generating a calendar

Recursive CTEs can also generate rows that don't exist in any table — for example every month of 2025, so months without orders still show 0:

sql · try it yourself
WITH RECURSIVE months(m) AS (
  SELECT '2025-01-01'
  UNION ALL
  SELECT date(m, '+1 month') FROM months WHERE m < '2025-12-01'
)
SELECT substr(m, 1, 7) AS month,
       (SELECT COUNT(*) FROM orders WHERE substr(order_date, 1, 7) = substr(m, 1, 7)) AS orders
FROM months
WHERE m >= '2025-08-01';
month   | orders
--------+-------
2025-08 | 4
2025-09 | 4
2025-10 | 4
2025-11 | 0
2025-12 | 0
(5 rows)
Database Recursive CTE keyword
SQLite, PostgreSQL, MySQL 8+ WITH RECURSIVE
SQL Server, Oracle WITH (no RECURSIVE keyword)

Tip: Always give a recursive CTE a stopping condition (WHERE n < 5, or a join that eventually finds nothing). Without one, it runs forever — or until the database aborts it.

Test yourself

Which keyword starts a CTE?

  1. CTE
  2. WITH
  3. DEFINE
  4. TEMP

What are the two parts of a recursive CTE?

  1. SELECT and WHERE
  2. An anchor query and a recursive query joined with UNION ALL
  3. Two CTEs separated by a comma
  4. A JOIN and a GROUP BY

When does a recursive CTE stop?

  1. After 100 rows
  2. When the recursive step produces no new rows
  3. Never
  4. After one iteration