Common Table Expressions (WITH): Writing Readable SQL in Steps
How the WITH clause names intermediate results so a complex query reads top to bottom: syntax, chaining and reusing CTEs, scope rules, CTEs versus derived tables and views, materialization and performance, data-modifying CTEs in PostgreSQL, and dialect differences.
kvi5hnuCode Sprout team member12 min readOn this page
The previous article showed derived tables: subqueries in FROM that work as temporary, unnamed tables. They're powerful, but a query that needs three or four steps ends up with derived tables nested inside derived tables. You have to read it from the innermost parentheses outward, and if two steps need the same intermediate result, you write it twice.
A common table expression, or CTE, solves both problems. The WITH clause gives each intermediate result a name, at the top of the statement, and the main query and later CTEs refer to it by that name. The query then reads from top to bottom, one step at a time, like a list of instructions.
This article covers ordinary CTEs. The next article covers recursive CTEs, which can refer to themselves and walk hierarchies.
The syntax
WITH name AS (
SELECT ... -- the CTE's query
)
SELECT ... -- the main query, which can use "name" like a table
FROM name;
WITH comes before the main SELECT and defines one or more named queries. Each one is available to the statement as if it were a table. Here's a single CTE that computes each order's value:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
\pset null '(null)'
-- One named step: the value of each order
WITH order_values AS (
SELECT o.order_id, o.customer_id, o.status,
SUM(oi.qty * oi.unit_price) AS value
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
GROUP BY o.order_id, o.customer_id, o.status
)
SELECT order_id, customer_id, status, value
FROM order_values
ORDER BY order_id;
order_id | customer_id | status | value
----------+-------------+-----------+--------
101 | 1 | shipped | 297.99
102 | 2 | shipped | 69.00
103 | 1 | delivered | 154.45
104 | 3 | pending | 489.00
105 | 4 | cancelled | 54.00
106 | (null) | shipped | 16.00
(6 rows)
On its own, that's no better than a derived table. The benefit comes when you chain steps.
Building a query in steps
Several CTEs can be defined in one WITH clause, separated by commas. Each can use the ones defined before it. Here's a customer segmentation report in three steps:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Three steps, each reading the one before
WITH order_values AS (
SELECT o.order_id, o.customer_id, o.status,
SUM(oi.qty * oi.unit_price) AS value
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
GROUP BY o.order_id, o.customer_id, o.status
),
customer_values AS (
SELECT customer_id, COUNT(*) AS orders, SUM(value) AS total
FROM order_values
WHERE status <> 'cancelled'
AND customer_id IS NOT NULL
GROUP BY customer_id
),
segments AS (
SELECT customer_id, orders, total,
CASE WHEN total >= 300 THEN 'high' ELSE 'standard' END AS segment
FROM customer_values
)
SELECT c.name, s.orders, s.total, s.segment
FROM segments s
JOIN customers c ON c.customer_id = s.customer_id
ORDER BY s.total DESC;
name | orders | total | segment
------------+--------+--------+----------
Chen Wei | 1 | 489.00 | high
Asha Rao | 2 | 452.44 | high
Ben Okafor | 1 | 69.00 | standard
(3 rows)

Each step does one job:
order_valuesturns order lines into one row per order with its value.customer_valuesreadsorder_values, removes cancelled and guest orders, and totals per customer.segmentsreadscustomer_valuesand labels each customer.- The main query joins the segments to
customersto show names.
Compare it with the same logic written as nested derived tables: the order-value query would sit three levels deep, inside the customer query, inside the segment query, inside the main query. Each step would have to be read from the inside out.
Steps also make a query easier to develop and debug. While writing the report, you can end the statement with SELECT * FROM customer_values to check that step's output before adding the next. When a number looks wrong, check each CTE in turn.
The comma between CTEs is easy to forget, and WITH appears only once: WITH a AS (...), b AS (...), not WITH a AS (...) WITH b AS (...).
Reusing a CTE
A CTE can be referenced several times in the same statement, which a derived table can't:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- One CTE used three times: customers whose total beats the average total
WITH customer_totals AS (
SELECT o.customer_id, SUM(oi.qty * oi.unit_price) AS total
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.customer_id IS NOT NULL
GROUP BY o.customer_id
)
SELECT ct.customer_id,
ct.total,
ROUND((SELECT AVG(total) FROM customer_totals), 2) AS avg_total
FROM customer_totals ct
WHERE ct.total > (SELECT AVG(total) FROM customer_totals)
ORDER BY ct.customer_id;
-- A column list after the CTE name renames its columns
WITH cheap (product, cost) AS (
SELECT name, price FROM products WHERE price < 30
)
SELECT product, cost FROM cheap ORDER BY cost;
customer_id | total | avg_total
-------------+--------+-----------
1 | 452.44 | 266.11
3 | 489.00 | 266.11
(2 rows)
product | cost
------------------+-------
Merino socks | 16.00
Basecamp lantern | 27.00
(2 rows)
The first query refers to customer_totals three times: as the main table, in the SELECT list to show the average, and in WHERE to compare with it. Without a CTE, the grouping query would have to be written out three times, and kept identical by hand whenever it changed.
The second query shows the optional column list: cheap (product, cost) names the CTE's columns, overriding the names from its SELECT. It's useful when the inner query's column names are long or computed, and it's required in some databases for recursive CTEs.
Scope rules
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- 1. A CTE exists only for the statement it belongs to
WITH t AS (SELECT 1 AS x)
SELECT x FROM t;
SELECT x FROM t;
-- 2. A CTE can't refer to one defined after it
WITH a AS (SELECT y FROM b),
b AS (SELECT 1 AS y)
SELECT y FROM a;
-- 3. A CTE with a table's name hides the table inside the statement
WITH products AS (SELECT 'not the real table' AS name)
SELECT name FROM products;
x
---
1
(1 row)
psql:/workspace/solution.sql:65: ERROR: relation "t" does not exist
LINE 1: SELECT x FROM t;
^
psql:/workspace/solution.sql:70: ERROR: relation "b" does not exist
LINE 1: WITH a AS (SELECT y FROM b),
^
DETAIL: There is a WITH item named "b", but it cannot be referenced from this part of the query.
HINT: Use WITH RECURSIVE, or re-order the WITH items to remove forward references.
name
--------------------
not the real table
(1 row)
- A CTE belongs to one statement. It disappears when the statement ends, so the second
SELECT x FROM tfails. To reuse a result across statements, you need a view (article 56) or a temporary table. - A CTE can only refer to CTEs defined before it.
arefers tob, which comes later, so the query fails. The hint mentionsWITH RECURSIVE: in PostgreSQL, addingRECURSIVElets the CTEs refer to each other in any order. Simply reordering them is the cleaner fix. - A CTE with the same name as a table hides that table for the whole statement. The
productsCTE replaces the realproductstable, without any warning. Choose CTE names that don't collide with table names.
A CTE can be defined inside a subquery, too, as in SELECT * FROM (WITH x AS (...) SELECT ...) AS s. Its scope is then just that subquery.
CTEs, derived tables and views
All three name or encapsulate a query. Here's how they differ:
| Derived table | CTE | View | |
|---|---|---|---|
| Defined | inside FROM | in WITH at the top of the statement | CREATE VIEW, stored in the database |
| Lifetime | one query | one statement | until dropped |
| Reusable within the statement | no, must be repeated | yes, by name | yes |
Can refer to other tables in the same FROM | only with LATERAL | no | no |
| Typical use | a single inline step | multi-step queries, reuse, recursion | logic shared by many queries and users |
A useful rule: if the intermediate result is needed by one query, use a CTE. If many queries need it, create a view.
How CTEs are executed
A CTE can be run in two ways:
- Inlined: the database substitutes the CTE's query wherever it's used, exactly like a derived table, and optimizes everything together.
- Materialized: the database computes the CTE once, stores the result in a temporary work area, and reads from it wherever it's used.
Inlining lets the optimizer push conditions from the main query into the CTE and use indexes. Materializing avoids recomputing an expensive CTE that's used several times, but the stored result has no indexes, and the main query's conditions can't reach inside it.
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
-- Used once and side-effect free: PostgreSQL inlines the CTE, and the filters merge
EXPLAIN (COSTS OFF)
WITH dear AS (SELECT * FROM products WHERE price > 50)
SELECT name FROM dear WHERE category = 'tents';
-- MATERIALIZED forces it to be computed first, as a separate step
EXPLAIN (COSTS OFF)
WITH dear AS MATERIALIZED (SELECT * FROM products WHERE price > 50)
SELECT name FROM dear WHERE category = 'tents';
QUERY PLAN
----------------------------------------------------------------------------
Seq Scan on products
Filter: ((price > '50'::numeric) AND ((category)::text = 'tents'::text))
(2 rows)
QUERY PLAN
----------------------------------------------
CTE Scan on dear
Filter: ((category)::text = 'tents'::text)
CTE dear
-> Seq Scan on products
Filter: (price > '50'::numeric)
(5 rows)
In the first plan, PostgreSQL has inlined the CTE: there's a single scan of products with both filters, price > 50 from the CTE and category = 'tents' from the main query, combined. In the second, MATERIALIZED forces the CTE to be computed first, as a separate CTE dear step, and the main query's filter is applied afterwards to its output, a CTE Scan.
What each database does:
- PostgreSQL 12 and later inline a CTE automatically if it's referenced once, isn't recursive, and has no side effects. A CTE referenced twice or more is materialized. You can override the choice with
AS MATERIALIZEDorAS NOT MATERIALIZED. Before version 12, PostgreSQL always materialized CTEs, which is why older advice describes CTEs as an "optimization fence". - MySQL 8.0 and MariaDB either merge a CTE into the main query or materialize it, based on the optimizer's choice.
- SQL Server always inlines CTEs: it never stores the result, so a CTE referenced three times is evaluated three times.
- Oracle decides by itself, and usually materializes a CTE that's referenced more than once.
- SQLite decides by itself, and since version 3.35 accepts the same
MATERIALIZEDandNOT MATERIALIZEDhints as PostgreSQL.
In practice, write CTEs for readability and check the plan (article 67) only when a query is slow. If an expensive CTE is used several times in SQL Server, a temporary table may be faster. If a materialized CTE prevents an index from being used in PostgreSQL, NOT MATERIALIZED can help.
Data-modifying CTEs in PostgreSQL
In PostgreSQL, a CTE can contain INSERT, UPDATE or DELETE with a RETURNING clause, and the rows it returns can be used by the rest of the statement:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- PostgreSQL: a CTE can contain INSERT, UPDATE or DELETE ... RETURNING
WITH gone_lines AS (
DELETE FROM order_items
WHERE order_id IN (SELECT order_id FROM orders WHERE status = 'cancelled')
RETURNING order_id
),
gone_orders AS (
DELETE FROM orders
WHERE status = 'cancelled'
RETURNING order_id
)
SELECT (SELECT COUNT(*) FROM gone_orders) AS orders_deleted,
(SELECT COUNT(*) FROM gone_lines) AS lines_deleted;
SELECT COUNT(*) AS orders_left FROM orders;
orders_deleted | lines_deleted
----------------+---------------
1 | 1
(1 row)
orders_left
-------------
5
(1 row)
The statement deletes the cancelled order's lines and the order itself, and reports what it deleted. This is useful for moving rows between tables in one statement, for example deleting old rows and inserting them into an archive table using the deleted rows that RETURNING produces.
Some rules make data-modifying CTEs behave differently from ordinary ones:
- They always run to completion, exactly once, even if the main query doesn't read their output.
- All parts of the statement see the data as it was before the statement started. The sub-statements can't see each other's changes. Their results are visible only through
RETURNING. - The order in which the sub-statements run isn't defined, so don't make two of them modify the same rows.
Here, the foreign key from order_items to orders is checked at the end of the statement, after both deletes, so deleting the order and its lines together doesn't violate it. Other databases don't support data-modifying CTEs. SQL Server, by contrast, lets a CTE be the target of UPDATE or DELETE (WITH d AS (...) DELETE FROM d WHERE ...), which is a different feature (article 33). Article 34 covers RETURNING in more detail.
CTEs in other statements
WITH can be used before INSERT, UPDATE and DELETE, not only SELECT. The placement varies:
-- PostgreSQL, SQL Server, SQLite: WITH before the statement
WITH recent AS (SELECT * FROM orders WHERE placed_on >= DATE '2026-03-15')
INSERT INTO recent_orders SELECT * FROM recent;
-- MySQL, Oracle: WITH after INSERT ... (it belongs to the SELECT part)
INSERT INTO recent_orders
WITH recent AS (SELECT * FROM orders WHERE placed_on >= '2026-03-15')
SELECT * FROM recent;
In SQL Server, the statement before a WITH must end with a semicolon, because WITH is also used for table hints. That's why you often see SQL Server code that starts with ;WITH. Ending every statement with a semicolon avoids the problem.
Writing good CTEs
- Give each CTE a name that says what one row is:
order_values,customer_totals,monthly_sales. The main query then reads almost like a sentence. - One job per CTE. If a CTE joins, filters, groups and classifies, split it.
- Don't wrap a simple query in a CTE.
WITH t AS (SELECT * FROM products) SELECT * FROM tadds nothing. - Watch the grain. Each step's output should have a clear grain, such as one row per order, so the next step can't fan out by accident (article 17).
- Check intermediate steps by temporarily selecting from them.
What's current
- PostgreSQL 12 (2019) stopped materializing every CTE and added the
MATERIALIZEDandNOT MATERIALIZEDkeywords. If you read that "CTEs are an optimization fence in PostgreSQL", that advice is about older versions. - SQLite 3.35 (2021) added the same keywords.
- CTEs are supported by every major database: PostgreSQL, SQL Server, Oracle, SQLite (since 3.8.3), MySQL (since 8.0) and MariaDB (since 10.2). MySQL 5.7 and older have none, which still matters for legacy systems.
Common questions
Is a CTE faster than a subquery? Usually neither is faster, because modern optimizers often inline the CTE and produce the same plan. When a CTE is materialized, it can be faster, if it's reused, or slower, if it stops filters and indexes from being used.
Can I index a CTE? No. If you need an indexed intermediate result, create a temporary table and index it.
Can I use a CTE in several queries? No, it exists for one statement only. Use a view or a temporary table.
Can a CTE refer to another CTE?
Yes, to any CTE defined before it in the same WITH clause.
Can I use ORDER BY inside a CTE?
PostgreSQL and MySQL accept it, but the order isn't guaranteed to carry through to the result. SQL Server rejects it unless the CTE has TOP or OFFSET. Sort in the main query.
Why does SQL Server code start with ;WITH?
Because WITH must follow a statement terminator in SQL Server, and some developers put the semicolon at the start to be safe. Ending the previous statement with ; is cleaner.
What's the difference between a CTE and a temporary table? A CTE is part of one statement and isn't stored, unless the database decides to materialize it while the statement runs. A temporary table is a real table that lasts until the session ends, can be indexed and can be used by many statements.
Do CTEs work in views?
Yes. A view's query can start with WITH.
Summary
WITH name AS (query)defines a named intermediate result that the rest of the statement can use like a table.- Several CTEs, separated by commas, turn a complex query into readable steps, each using the ones before it.
- Unlike a derived table, a CTE can be referenced several times in one statement.
- A CTE lasts for one statement, must be defined before it's referenced, and hides any table with the same name.
- Databases either inline a CTE or materialize it. PostgreSQL 12+ inlines single-use CTEs and accepts
MATERIALIZEDandNOT MATERIALIZEDhints. SQL Server always inlines. - In PostgreSQL, a CTE can contain
INSERT,UPDATEorDELETE ... RETURNING, and all parts of the statement see the data as it was when the statement started.
Practice questions
Rewrite this query with a CTE: SELECT category, n FROM (SELECT category, COUNT(*) AS n FROM products GROUP BY category) AS t WHERE n > 1;
Answer
WITH category_counts AS (
SELECT category, COUNT(*) AS n
FROM products
GROUP BY category
)
SELECT category, n
FROM category_counts
WHERE n > 1;
It returns lighting, packs and tents, each with 2. The CTE's name now documents what the inner query produces.
Write a query with two CTEs: the first computes the value of each order, and the second the average order value. The main query lists orders worth more than the average.
Answer
WITH order_values AS (
SELECT order_id, SUM(qty * unit_price) AS value
FROM order_items
GROUP BY order_id
),
average AS (
SELECT AVG(value) AS avg_value FROM order_values
)
SELECT ov.order_id, ov.value
FROM order_values ov
CROSS JOIN average a
WHERE ov.value > a.avg_value
ORDER BY ov.value DESC;
The average order value is 1080.44 / 6 = 180.07, so orders 104 (489.00) and 101 (297.99) are listed. The single-row average CTE is combined with every order by a cross join.
This statement fails. Why, and what are two ways to fix it? WITH totals AS (SELECT customer_id, SUM(value) AS total FROM order_values GROUP BY customer_id), order_values AS (SELECT ...) SELECT * FROM totals;
Answer
totals refers to order_values, which is defined after it, and a non-recursive CTE can only refer to CTEs defined before it. Either put order_values first, which is the clear fix, or, in PostgreSQL, write WITH RECURSIVE, which allows references in any order.
In PostgreSQL 17, a CTE is referenced once in the main query, and the main query filters on an indexed column of its result. Will the filter be pushed into the CTE? What if the CTE is referenced twice?
Answer
Referenced once, the CTE is inlined (it isn't recursive and has no side effects), so the filter is merged into its query and the index can be used. Referenced twice, it's materialized by default, so the filter is applied to the stored result and can't use the index. Writing AS NOT MATERIALIZED makes PostgreSQL inline it in both places instead.
Why does WITH t AS (SELECT 1 AS x) SELECT * FROM t; SELECT * FROM t; fail on the second statement?
Answer
A CTE belongs only to the statement it's defined in. The first SELECT ends at the semicolon, and t no longer exists for the second statement. Repeat the WITH, or create a view or a temporary table if several statements need the result.
Previous: Correlated Subqueries, Derived Tables and LATERAL Joins
Next: Recursive CTEs: Sequences, Hierarchies and Graph Walks

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.