Skip to content

Common table expressions (WITH)

View as Markdown

A common table expression (CTE) is a named subquery defined at the start of a statement with the WITH clause. The rest of the statement can refer to it like a table, as many times as needed. CTEs break a long query into readable steps, let one step build on another, and, with RECURSIVE, generate rows by repeating a query on its own output.

A CTE exists only for the statement that defines it.

WITH [RECURSIVE]
cte_name [(column_name, ...)] AS (<subquery>)
[, cte_name [(column_name, ...)] AS (<subquery>) ...]
<statement>
  • cte_name: the name the statement uses to refer to the CTE. Names must be unique within one WITH clause.
  • column_name: optional names for the CTE's columns. Their number must match the subquery's columns.
  • subquery: the query that defines the CTE. It can refer to CTEs defined earlier in the same WITH clause.
  • RECURSIVE: allows a CTE to refer to itself (see Recursive CTEs).
  • statement: the statement that uses the CTEs: a SELECT, or one of the statements listed in CTEs in other statements.

Each CTE can build on the ones before it. The query below first computes the value of every 2025 order, then sums those values per customer, and finally joins the totals with the customer names:

WITH
order_totals AS (
SELECT o.id, o.customer_id,
SUM(oi.quantity * p.unit_price * (100 - oi.discount_pct) / 100) AS total
FROM orders o
JOIN order_items oi ON oi.order_id = o.id
JOIN product p ON p.id = oi.product_id
WHERE o.order_date BETWEEN DATE'2025-01-01' AND DATE'2025-12-31'
GROUP BY o.id, o.customer_id),
customer_totals AS (
SELECT customer_id, COUNT(*) AS orders, SUM(total) AS spent
FROM order_totals
GROUP BY customer_id)
SELECT c.company_name, ct.orders, ct.spent
FROM customer_totals ct JOIN customer c ON c.id = ct.customer_id
ORDER BY ct.spent DESC
LIMIT 5;
company_name orders spent
Young and Sons 13 6938.50
Mayer, Carroll and Owens 11 5252.00
Price, Whitney and Carr 8 5242.55
Johnson and Sons 7 4773.24
Gallagher-Cohen 8 4497.20

A statement can also use several independent CTEs side by side:

WITH
frequent AS (
SELECT customer_id FROM orders GROUP BY customer_id HAVING COUNT(*) >= 39),
last_orders AS (
SELECT customer_id, MAX(order_date) AS last_order FROM orders GROUP BY customer_id)
SELECT f.customer_id, l.last_order
FROM frequent f JOIN last_orders l ON l.customer_id = f.customer_id
ORDER BY f.customer_id;
customer_id last_order
440 2025-12-27
444 2025-09-06
812 2025-12-10

Name the CTE's columns after its name. The list must have as many names as the subquery has columns. The CTE below, which reads graph data through the part_of edges, returns each category with its number of products and highest price:

WITH category_prices (category, products, top_price) AS (
SELECT c.name, COUNT(*), MAX(p.unit_price)
FROM MATCH (p:product)-[:part_of]->(c:category)
GROUP BY c.name)
SELECT * FROM category_prices
ORDER BY top_price DESC
LIMIT 3;
category products top_price
Beverages 12 263.50
Meat/Poultry 6 123.79
Jackets 362 99.00

Without a column list, the columns take the names of the subquery's select list. Expressions without an alias are named after their text, which is awkward to refer to:

WITH category_prices AS (
SELECT c.name, COUNT(*), MAX(p.unit_price)
FROM MATCH (p:product)-[:part_of]->(c:category)
GROUP BY c.name)
SELECT * FROM category_prices
ORDER BY 3 DESC
LIMIT 3;
name count(*) max(p.unit_price)
Beverages 12 263.50
Meat/Poultry 6 123.79
Jackets 362 99.00

With WITH RECURSIVE, a CTE can refer to itself. A recursive CTE has two parts joined by UNION ALL:

  • The non-recursive part, which produces the starting rows;
  • The recursive part, which refers to the CTE by name and produces new rows from the rows of the previous step.

CoraDB evaluates it like this:

  1. Run the non-recursive part and add its rows to the result.
  2. Run the recursive part on the rows produced by the previous step and add the new rows to the result.
  3. Repeat step 2 until a step produces no rows, or until the maximum number of recursions is reached.

A common use is generating a series, such as one row per month. Joined with orders through a LEFT JOIN, the series gives a monthly report that includes every month, even one without orders:

WITH RECURSIVE months (month_start) AS (
SELECT DATE'2025-01-01'
UNION ALL
SELECT ADD_MONTHS(month_start, 1) FROM months WHERE month_start < DATE'2025-12-01')
SELECT m.month_start, COUNT(o.id) AS orders
FROM months m LEFT JOIN orders o
ON o.order_date >= m.month_start AND o.order_date < ADD_MONTHS(m.month_start, 1)
GROUP BY m.month_start
ORDER BY m.month_start;
month_start orders
2025-01-01 51
2025-02-01 50
2025-03-01 46
2025-04-01 54
2025-05-01 56
2025-06-01 62
2025-07-01 50
2025-08-01 69
2025-09-01 67
2025-10-01 76
2025-11-01 110
2025-12-01 95

For hierarchies stored in a single table (an employee and their manager, a part and its assembly), recursive CTEs work the same way: the non-recursive part selects the top rows and the recursive part joins the table to the CTE. For data stored as a graph, a MATCH path pattern is usually simpler.

The recursive part must refer to the CTE directly in its FROM clause. Referring to it inside a nested subquery is an error:

WITH RECURSIVE n (x) AS (
SELECT 1
UNION ALL
SELECT * FROM (SELECT n.x + 1 FROM n WHERE n.x < 5))
SELECT * FROM n;
ERROR: Recursive CTE 'n' must be referenced directly in its recursive query.

A recursive CTE whose recursive part never stops producing rows would run forever. The cte_max_recursions parameter stops it after a number of steps: the default is 2,000, the minimum 2 and the maximum 1,000,000. Set it for your session with SET SYSTEM PARAMETERS:

SET SYSTEM PARAMETERS 'cte_max_recursions=5';
WITH RECURSIVE months (month_start) AS (
SELECT DATE'2025-01-01'
UNION ALL
SELECT ADD_MONTHS(month_start, 1) FROM months WHERE month_start < DATE'2025-12-01')
SELECT COUNT(*) FROM months;
ERROR: Maximum recursions 5 reached executing CTE.

Two CTEs in the same WITH clause cannot have the same name:

WITH
big_orders AS (SELECT id FROM orders WHERE shipping_cost > 30),
big_orders AS (SELECT id FROM orders WHERE shipping_cost > 40)
SELECT COUNT(*) FROM big_orders;
ERROR: CTE name ambiguity, there are more than one CTEs with the same name: 'big_orders'.

A CTE cannot contain its own WITH clause. Define all CTEs at the same level instead:

WITH recent AS (
WITH december AS (SELECT id FROM orders WHERE order_date >= DATE'2025-12-01')
SELECT * FROM december)
SELECT COUNT(*) FROM recent;
ERROR: Nested WITH clauses are not supported.

Besides SELECT, a WITH clause can be used in CREATE TABLE ... AS SELECT, INSERT ... SELECT, REPLACE ... SELECT, UPDATE and DELETE. These examples change data; to keep the sample database unchanged, start corasql with --no-auto-commit and finish with ROLLBACK;.

In CREATE TABLE ... AS, the WITH clause comes after AS:

CREATE TABLE monthly_orders AS
WITH RECURSIVE months (month_start) AS (
SELECT DATE'2025-10-01'
UNION ALL
SELECT ADD_MONTHS(month_start, 1) FROM months WHERE month_start < DATE'2025-12-01')
SELECT m.month_start, COUNT(o.id) AS orders
FROM months m LEFT JOIN orders o
ON o.order_date >= m.month_start AND o.order_date < ADD_MONTHS(m.month_start, 1)
GROUP BY m.month_start;
SELECT * FROM monthly_orders ORDER BY 1;
month_start orders
2025-10-01 76
2025-11-01 110
2025-12-01 95

In INSERT and REPLACE, it comes before the SELECT:

INSERT INTO monthly_orders
WITH RECURSIVE months (month_start) AS (
SELECT DATE'2026-01-01'
UNION ALL
SELECT ADD_MONTHS(month_start, 1) FROM months WHERE month_start < DATE'2026-02-01')
SELECT month_start, 0 FROM months;
2 rows affected.

In UPDATE and DELETE, the WITH clause comes first and the CTE can be joined or used in subqueries. Add 25 units of stock to every product that has sold at least 150 units:

WITH best_sellers AS (
SELECT product_id, SUM(quantity) AS sold
FROM order_items
GROUP BY product_id)
UPDATE product p JOIN best_sellers b ON p.id = b.product_id
SET p.units_in_stock = p.units_in_stock + 25
WHERE b.sold >= 150;
26 rows affected.

Remove the months that are later than the last order:

WITH last_sale AS (SELECT MAX(order_date) AS last_day FROM orders)
DELETE FROM monthly_orders
WHERE month_start > (SELECT last_day FROM last_sale);
2 rows affected.