Tablux

Tablux › Guides › SQL CTE

Guide

SQL CTEs (common table expressions), with examples

A CTE (common table expression) is a named, temporary result set that you define with WITH name AS (SELECT …) at the start of a statement and then use like a table in that statement only. CTEs split a long query into readable steps, and WITH RECURSIVE can walk trees and generate series. They work in PostgreSQL, MySQL 8.0+, MariaDB 10.2+, SQLite and SQL Server.

CTE syntax

The examples use two small tables. orders is the same table as in the window functions guide; customers is new:

-- orders(id, customer_id, ordered_at, total): 8 orders from January to March 2026
-- customers(id, name, country)
INSERT INTO customers VALUES
  (1, 'Ana', 'Spain'), (2, 'Ben', 'Canada'), (3, 'Chen', NULL), (4, 'Dara', 'Spain');

A CTE is a query with a name, written before the main query. Here it adds up each customer's orders, and the main query joins the result to customers:

WITH customer_totals AS (
  SELECT customer_id, COUNT(*) AS orders, SUM(total) AS spent
  FROM orders
  GROUP BY customer_id
)
SELECT c.name, t.orders, t.spent
FROM customer_totals t
JOIN customers c ON c.id = t.customer_id
WHERE t.spent > 250
ORDER BY t.spent DESC;
nameordersspent
Chen2350.00
Ben3255.00

The CTE exists only while this statement runs. You can name its columns in a list instead of with aliases: WITH customer_totals (customer_id, orders, spent) AS (…). In SQL Server, end the statement before a WITH with a semicolon, or it is read as part of that statement.

Multiple CTEs in one query

Separate CTEs with commas, and write WITH only once. A later CTE can read an earlier one, which is how you build a query in steps:

WITH customer_totals AS (
  SELECT customer_id, SUM(total) AS spent
  FROM orders
  GROUP BY customer_id
),
average AS (
  SELECT AVG(spent) AS avg_spent
  FROM customer_totals
)
SELECT t.customer_id, t.spent,
       ROUND(t.spent - a.avg_spent, 2) AS vs_average
FROM customer_totals t
CROSS JOIN average a
ORDER BY t.spent DESC;
customer_idspentvs_average
3350.0073.33
2255.00-21.67
1225.00-51.67

Each step has a name that says what it holds, so the main query reads like a summary. The same logic with nested subqueries works, but you would have to repeat the customer_totals query inside the average.

Recursive CTEs: walk a tree

A recursive CTE refers to itself. It has two parts joined by UNION ALL: an anchor query that runs once, and a recursive query that runs again and again on the rows produced by the previous round, until it returns no rows. The classic use is a hierarchy stored as a parent id:

CREATE TABLE employees (
  id         INT PRIMARY KEY,
  name       VARCHAR(50) NOT NULL,
  manager_id INT
);
INSERT INTO employees VALUES
  (1, 'Maya', NULL), (2, 'Omar', 1), (3, 'Lena', 1),
  (4, 'Raj', 2), (5, 'Sofia', 2), (6, 'Tom', 4);

List everyone under Maya with their depth and reporting line:

-- PostgreSQL and SQLite
WITH RECURSIVE org AS (
  SELECT id, name, manager_id, 1 AS depth, CAST(name AS TEXT) AS path
  FROM employees
  WHERE manager_id IS NULL                 -- anchor: the top of the tree
  UNION ALL
  SELECT e.id, e.name, e.manager_id, o.depth + 1, o.path || ' > ' || e.name
  FROM employees e
  JOIN org o ON e.manager_id = o.id        -- recursive step: direct reports
)
SELECT id, name, depth, path
FROM org
ORDER BY path;
-- MySQL 8.0 and MariaDB: same query, different cast and concatenation
  SELECT id, name, manager_id, 1 AS depth, CAST(name AS CHAR(200)) AS path
  ...
  SELECT e.id, e.name, e.manager_id, o.depth + 1, CONCAT(o.path, ' > ', e.name)
idnamedepthpath
1Maya1Maya
3Lena2Maya > Lena
2Omar2Maya > Omar
4Raj3Maya > Omar > Raj
6Tom4Maya > Omar > Raj > Tom
5Sofia3Maya > Omar > Sofia

RECURSIVE is required in PostgreSQL, MySQL and MariaDB and optional in SQLite; SQL Server does not use the keyword at all. The cast in the anchor matters: the anchor fixes each column's type. PostgreSQL refuses a mismatch (recursive query "org" column 5 has type character varying(50) in non-recursive term but type character varying overall), and MySQL cuts longer values to the anchor's length, or fails with Data too long in strict mode.

Walk up the tree

Swap the join to go from a row to its ancestors, for example everyone above Tom:

WITH RECURSIVE bosses AS (
  SELECT id, name, manager_id FROM employees WHERE name = 'Tom'
  UNION ALL
  SELECT e.id, e.name, e.manager_id
  FROM employees e
  JOIN bosses b ON e.id = b.manager_id
)
SELECT name FROM bosses;
-- Tom, Raj, Omar, Maya

The same pattern works for categories and subcategories, folders, bills of materials and threaded comments.

Generate a series of dates

A recursive CTE can also make rows from nothing. A list of months, joined to the orders, shows months with no orders as zero instead of leaving them out:

-- PostgreSQL
WITH RECURSIVE months AS (
  SELECT DATE '2026-01-01' AS month
  UNION ALL
  SELECT CAST(month + INTERVAL '1 month' AS DATE)
  FROM months
  WHERE month < DATE '2026-04-01'
)
SELECT m.month, COUNT(o.id) AS orders, COALESCE(SUM(o.total), 0) AS revenue
FROM months m
LEFT JOIN orders o
  ON o.ordered_at >= m.month AND o.ordered_at < m.month + INTERVAL '1 month'
GROUP BY m.month
ORDER BY m.month;
monthordersrevenue
2026-01-013245.00
2026-02-013340.00
2026-03-012245.00
2026-04-0100
-- MySQL / MariaDB: the step and the join condition
SELECT month + INTERVAL 1 MONTH FROM months WHERE month < DATE '2026-04-01'
... ON o.ordered_at >= m.month AND o.ordered_at < m.month + INTERVAL 1 MONTH

-- SQLite: dates are text, so use date()
SELECT '2026-01-01' AS month
UNION ALL
SELECT date(month, '+1 month') FROM months WHERE month < '2026-04-01'
... ON o.ordered_at >= m.month AND o.ordered_at < date(m.month, '+1 month')

In PostgreSQL, generate_series(DATE '2026-01-01', DATE '2026-04-01', INTERVAL '1 month') does the same without recursion.

Recursion limits and infinite loops

If the recursive step never stops returning rows (a typo in the join, or a cycle in the data such as A manages B and B manages A), the query runs until a limit stops it:

  • MySQL stops at cte_max_recursion_depth (default 1000) with an error.
  • MariaDB stops at max_recursive_iterations (1000 on the 10.11 server we tested) with only a warning (1931) and returns the rows it has, so a result can be silently incomplete. Run SHOW WARNINGS.
  • PostgreSQL and SQLite have no recursion limit. The query runs until it is cancelled or hits a statement timeout.
  • SQL Server stops at 100 levels unless you add OPTION (MAXRECURSION n); 0 means no limit.
-- MySQL: the default cte_max_recursion_depth is 1000
ERROR 3636 (HY000): Recursive query aborted after 1001 iterations.
Try increasing @@cte_max_recursion_depth to a larger value.

SET SESSION cte_max_recursion_depth = 100000;   -- MySQL
SET SESSION max_recursive_iterations = 100000;  -- MariaDB

To guard against cycles, keep a depth column and add WHERE depth < 20 to the recursive step, or use UNION instead of UNION ALL so that rows already seen are dropped (this only helps when the repeated rows are identical, so not together with a depth column). PostgreSQL 14 and later can detect cycles with the CYCLE clause, which marks the repeated row and stops there:

WITH RECURSIVE walk AS (
  SELECT src, dst FROM links WHERE src = 1
  UNION ALL
  SELECT l.src, l.dst FROM links l JOIN walk w ON l.src = w.dst
) CYCLE src SET is_cycle USING path
SELECT * FROM walk;

CTE vs subquery vs temporary table vs view

Lives forReusableGood for
CTE (WITH)One statementWithin that statementReadable multi-step queries, recursion
Subquery / derived tableOne statementNo: repeat it to reuse itA single small step
Temporary tableThe session (connection)Across statements in the sessionLarge intermediate results you query several times; can be indexed
ViewUntil droppedBy anyone with accessLogic that many queries and users share

A non-recursive CTE and a subquery in FROM are usually interchangeable, and modern optimizers often run them the same way. Choose a CTE for readability or when a step is used twice. Choose a temporary table when the intermediate result is large and several separate statements need it, or when it would benefit from an index. Choose a view when the logic should be shared.

Are CTEs materialized? Performance by database

A CTE can be inlined (merged into the main query, so filters reach the underlying table's indexes) or materialized (computed once into a temporary result that the main query then reads).

PostgreSQL 12 and later inline a CTE if it is not recursive, has no side effects and is referenced only once. Otherwise it is materialized. You can override this with AS MATERIALIZED or AS NOT MATERIALIZED. Before version 12, every CTE was materialized, which made CTEs an “optimization fence”: a filter in the main query could not use an index inside the CTE. The difference shows in the plan:

EXPLAIN WITH t AS (SELECT * FROM orders) SELECT * FROM t WHERE id = 3;
--  Index Scan using orders_pkey on orders     (inlined: uses the index)

EXPLAIN WITH t AS MATERIALIZED (SELECT * FROM orders) SELECT * FROM t WHERE id = 3;
--  CTE Scan on t  Filter: (id = 3)
--    CTE t -> Seq Scan on orders            (computed first, then filtered)

MySQL 8.0 treats a CTE like a derived table: it merges it into the main query when it can, and otherwise materializes it once, even if the query references it several times. Recursive CTEs are always materialized. There is no MATERIALIZED keyword (it is a syntax error); use the optimizer hints /*+ MERGE(cte) */ or /*+ NO_MERGE(cte) */ in the main SELECT.

SQLite 3.35.0 and later accept MATERIALIZED and NOT MATERIALIZED as hints. MariaDB (10.11) does not accept the keywords. SQL Server does not materialize CTEs: each reference runs the query again, so use a temporary table for an expensive result that you read several times.

If a CTE query is slow, compare its plan with the same query written as a subquery. When both are slow, the problem is usually a missing index, not the CTE.

Data-modifying CTEs in PostgreSQL

In PostgreSQL, a CTE can be an INSERT, UPDATE or DELETE with RETURNING, and the main query can use the returned rows. This moves rows between tables in one atomic statement:

-- PostgreSQL: move January orders to an archive table in one statement
WITH moved AS (
  DELETE FROM orders
  WHERE ordered_at < DATE '2026-02-01'
  RETURNING *
)
INSERT INTO orders_archive
SELECT * FROM moved;

Two rules to know. Every part of the statement sees the same snapshot of the data, so the main query does not see the CTE's changes in the table itself; RETURNING is the only way to pass them on. And data-modifying CTEs always run to completion, even if the main query never reads them.

MySQL, MariaDB and SQLite do not allow INSERT, UPDATE or DELETE inside a CTE. MySQL and SQLite do allow a WITH clause in front of an UPDATE or DELETE, so a CTE can choose which rows to change. MariaDB 10.11 rejects that too, so use a subquery there.

Which databases support CTEs

DatabaseWITH and WITH RECURSIVENotes
PostgreSQL8.4Data-modifying CTEs 9.1; inlining and MATERIALIZED 12; SEARCH / CYCLE 14
MySQL8.0Recursion limit cte_max_recursion_depth (1000); WITH can precede UPDATE and DELETE
MariaDB10.2Recursion limit max_recursive_iterations (1000 in 10.11); no WITH before UPDATE in 10.11
SQLite3.8.3MATERIALIZED / NOT MATERIALIZED hints 3.35.0
SQL ServerYesNo RECURSIVE keyword; recursion limit 100, change with OPTION (MAXRECURSION n); end the previous statement with a semicolon

The examples on this page were run on PostgreSQL 16, MySQL 8.0, MariaDB 10.11 and SQLite 3.45. MySQL 5.7 and older have no CTEs: rewrite the CTE as a derived table (a subquery in FROM).

Practice on real data

The free read-only PostgreSQL demo database has customers, orders, products and categories to try CTEs on; its tables have more columns than the examples here. Tablux connects to it, and to your own PostgreSQL, MySQL, MariaDB and SQLite databases, from a Mac, iPhone or iPad. If you would rather describe the result you want, the AI assistant writes the query into the editor for you to read and run.

Questions

What does CTE stand for in SQL?

Common table expression: a named temporary result set defined with WITH at the start of a statement and used like a table within that statement.

Is a CTE faster than a subquery?

Usually neither is faster. PostgreSQL 12+, MySQL 8.0 and SQLite can inline a simple CTE, so it runs like the equivalent subquery. Before PostgreSQL 12, CTEs were always materialized, which could be slower.

Can I use more than one CTE in a query?

Yes. Write WITH once and separate the CTEs with commas. Each CTE can refer to the ones defined before it.

How do I stop a recursive CTE from looping forever?

Make sure the recursive step eventually returns no rows: add a depth limit such as WHERE depth < 20, use UNION instead of UNION ALL, or use the CYCLE clause in PostgreSQL 14+.

Does MySQL support WITH and recursive CTEs?

Yes, from MySQL 8.0, including WITH RECURSIVE. MySQL 5.7 does not; use a derived table instead. MariaDB supports both from 10.2.

Can I use a CTE in UPDATE or DELETE?

In PostgreSQL, MySQL 8.0, SQLite and SQL Server, a WITH clause can come before UPDATE or DELETE. Only PostgreSQL lets the CTE itself be an INSERT, UPDATE or DELETE.

Updated 2026-11-25