Sub topic 2
Your first CTE: naming a result with WITH
A common table expression (CTE) gives a name to a query result so that the rest of the statement can use it like a table. This chapter covers the syntax, how a CTE relates to the derived table (a subquery in FROM) that you already know, and the errors people hit first. It assumes you can write SELECT, WHERE, ORDER BY, joins, and GROUP BY with aggregates such as SUM. Chaining several CTEs, scope rules, recursion, and execution behavior each get their own later chapter, so they appear here only briefly.
Sample data
The examples use two small tables. The statements below run unchanged on PostgreSQL, MySQL 8, SQLite, and SQL Server (SQL Server may need INT types adjusted only if you use stricter settings).
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name VARCHAR(50) NOT NULL
);
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL REFERENCES customers (id),
order_date DATE NOT NULL,
amount DECIMAL(10, 2) NOT NULL
);
INSERT INTO customers (id, name) VALUES
(1, 'Ada'), (2, 'Ben'), (3, 'Chen'), (4, 'Dara');
INSERT INTO orders (id, customer_id, order_date, amount) VALUES
(1, 1, '2026-01-05', 600.00),
(2, 1, '2026-02-10', 700.00),
(3, 2, '2026-01-20', 450.00),
(4, 2, '2026-03-02', 300.00),
(5, 3, '2026-03-15', 1000.00),
(6, 3, '2026-03-20', 1200.00);The per-customer totals are Ada 1300, Ben 750, and Chen 2200. Dara has no orders.
The problem: a derived table in the middle of a query
Suppose you want the names and total spend of customers who spent more than 1000. With a derived table, you write the aggregation inside the FROM clause:
SELECT c.name, t.total
FROM customers c
JOIN (
SELECT customer_id, SUM(amount) AS total
FROM orders
GROUP BY customer_id
) t ON t.customer_id = c.id
WHERE t.total > 1000;This works, but the reader meets the join condition (ON t.customer_id = c.id) only after reading the whole subquery. With one level of nesting that is tolerable. With three levels, you read from the inside out, and the alias t carries no meaning.
Your first CTE
A CTE moves the subquery to the top of the statement and gives it a name. The syntax is WITH name AS ( query ), followed by the main statement.
WITH order_totals AS (
SELECT customer_id, SUM(amount) AS total
FROM orders
GROUP BY customer_id
)
SELECT c.name, t.total
FROM customers c
JOIN order_totals t ON t.customer_id = c.id
WHERE t.total > 1000;The result is two rows: Ada with 1300.00 and Chen with 2200.00.
The query has two parts:
- The
WITHclause definesorder_totals. Its body is anySELECTthat is valid on its own. - The main statement, which comes after the closing parenthesis, uses
order_totalswherever a table name could appear.
Read top to bottom, the statement says "first compute the totals, then join them to customers and filter". The name order_totals tells the reader what the intermediate result is. A comment on a derived table's alias rarely does that.
What a CTE is and is not
A CTE exists for one statement only. When the statement ends, the name is gone. Nothing is stored in the schema, and nothing is visible to other sessions or later queries. That separates it from three similar objects:
| Object | Lifetime | Stored in schema | Typical use |
|---|---|---|---|
| CTE | One statement | No | Name an intermediate step inside a query |
| View | Until dropped | Yes (definition only) | Share a query definition across many queries |
| Temporary table | Session (or transaction) | Temporary, holds data | Keep an intermediate result across statements |
A CTE is also not guaranteed to be a physical table. The database may compute it once and keep the rows, or fold its definition into the main query. The materialization chapter covers this. For now, treat a CTE as a naming device and not as a cache.
Naming the columns
The columns of a CTE come from its SELECT list. Expressions need aliases so that the outer query can refer to them. Compare:
WITH order_totals AS (
SELECT customer_id, SUM(amount)
FROM orders
GROUP BY customer_id
)
SELECT * FROM order_totals;PostgreSQL names the second column sum, SQLite uses the text of the expression, and SQL Server rejects the statement because a column has no name. Add AS total and the behavior is the same everywhere.
You can also list the column names after the CTE name. The list overrides whatever names the SELECT produces:
WITH order_totals (customer_id, total) AS (
SELECT customer_id, SUM(amount)
FROM orders
GROUP BY customer_id
)
SELECT customer_id, total
FROM order_totals
ORDER BY total DESC;The list is matched by position, so it must have exactly as many names as the SELECT has columns. A mismatch is an error. The column list is required for recursive CTEs in some databases, so the habit is worth learning now. Many teams still prefer aliases inside the SELECT, because the name sits next to the expression it labels.
Using a CTE more than once
A derived table can be used in only one place, because its definition is part of the FROM clause. A CTE can be referenced several times in the same statement. This is a stronger reason to use one than readability alone. The query below finds customers whose total is above the average customer total:
WITH order_totals AS (
SELECT customer_id, SUM(amount) AS total
FROM orders
GROUP BY customer_id
)
SELECT c.name, t.total
FROM customers c
JOIN order_totals t ON t.customer_id = c.id
WHERE t.total > (SELECT AVG(total) FROM order_totals);The average of 1300, 750, and 2200 is about 1416.67, so only Chen is returned. Without the CTE, you would repeat the entire aggregation inside the scalar subquery. Duplicated logic tends to drift apart when someone edits one copy.
Whether the database runs the aggregation once or twice depends on the engine and its version. The result is the same either way. Do not assume the work is shared.
Refactoring a nested subquery step by step
A reliable way to practice is to convert an existing query. Take the derived-table query from earlier and apply these steps:
- Pick the innermost subquery, the one that does not refer to columns of the outer query.
- Copy it, with its parentheses, to the top of the statement after
WITH name AS. - Choose a name that describes the rows, not the operation.
order_totalsis better thansubq1. - Replace the original subquery with the name. If it had an alias, either reuse it or drop the alias and use the CTE name.
- Run both versions and compare the results.
Step 1 matters. A subquery that refers to the outer query's columns is a correlated subquery. A CTE cannot do that, because it is defined before the outer query's rows exist. Rewrite a correlated subquery as a join, with grouping inside the CTE where needed, before you move it.
-- Correlated: runs conceptually once per customer row
SELECT c.name,
(SELECT SUM(o.amount) FROM orders o WHERE o.customer_id = c.id) AS total
FROM customers c;
-- Refactored: the CTE groups once, the join matches rows
WITH order_totals AS (
SELECT customer_id, SUM(amount) AS total
FROM orders
GROUP BY customer_id
)
SELECT c.name, t.total
FROM customers c
LEFT JOIN order_totals t ON t.customer_id = c.id;Both queries return four rows, including Dara. The first query shows NULL for her total because SUM over zero rows is NULL. The second shows NULL because the LEFT JOIN finds no match. Using JOIN in place of LEFT JOIN would drop Dara, which is a common bug introduced during refactoring.
Which statements can follow WITH
The WITH clause is most often followed by SELECT. Most modern databases also accept it in front of INSERT, UPDATE, and DELETE, so you can name an intermediate result and use it in a write. Syntax details differ by product. In PostgreSQL, for example, a CTE can also contain the data-modifying statement itself, which a later chapter covers.
Here is a WITH clause in front of an INSERT. It records each customer's total in a summary table:
CREATE TABLE customer_totals (
customer_id INTEGER PRIMARY KEY,
total DECIMAL(10, 2) NOT NULL
);
WITH order_totals AS (
SELECT customer_id, SUM(amount) AS total
FROM orders
GROUP BY customer_id
)
INSERT INTO customer_totals (customer_id, total)
SELECT customer_id, total
FROM order_totals;This placement is accepted by PostgreSQL and SQLite. MySQL 8 and SQL Server expect the WITH clause inside the statement, after INSERT INTO ... (columns) or in front of the SELECT. The portable form puts it in front of the SELECT:
INSERT INTO customer_totals (customer_id, total)
WITH order_totals AS (
SELECT customer_id, SUM(amount) AS total
FROM orders
GROUP BY customer_id
)
SELECT customer_id, total
FROM order_totals;Oracle accepts only the second form for INSERT. If you write SQL for more than one product, prefer the second form.
Common errors and how to read them
The first CTE errors fall into a few groups.
- A statement before the WITH clause is not terminated. SQL Server requires the previous statement to end with a semicolon before
WITH. Without it, the parser readsWITHas a table hint and reports a syntax error nearWITH. Ending every statement with;avoids this. - A missing or extra comma. The
WITHkeyword appears once. Further CTEs are separated by commas, not by a secondWITH. Chaining is the next chapter's topic, but the rule shows up in the first mistakes people make. There must be no comma between the closing parenthesis of the last CTE and the main statement. - Unnamed columns. As shown earlier, an expression without an alias breaks in some databases and works with a surprising name in others.
- ORDER BY inside the CTE. SQL Server rejects
ORDER BYin a CTE body unless it is paired withTOP,OFFSET, orFOR XML. In other databases the clause is allowed, but the order does not carry to the outer query, because a table has no row order. PutORDER BYon the outer statement. - A CTE name that matches a real table. Inside the statement, the CTE name wins. A CTE called
ordershides the realorderstable, and a CTE whose body reads fromordersis not recursive unless the keyword says so. This can be useful when testing, but it often hides mistakes. Choose names that cannot collide, such asrecent_orders. - Using the name outside the statement. After the semicolon,
order_totalsno longer exists. Running a second query that mentions it gives a "relation does not exist" or "no such table" error.
When the CTE does not earn its place
A CTE is not always an improvement. The first query in this chapter could have used HAVING:
SELECT c.name, SUM(o.amount) AS total
FROM customers c
JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name
HAVING SUM(o.amount) > 1000;This version is shorter and just as clear. The CTE form pays off when:
- the intermediate result is referenced more than once,
- later steps build on earlier ones (the next chapter),
- the logic is long enough that a name helps the reader, or
- you need recursion, which only CTEs provide.
For a one-off aggregate with a single filter, the plain query is fine. Writing a CTE should be a choice you can justify, not a reflex.
Dialect support at a glance
| Database | CTE support | Notes |
|---|---|---|
| PostgreSQL | 8.4 and later | Data-modifying CTEs supported |
| MySQL | 8.0 and later | Not available in 5.7 |
| MariaDB | 10.2.1 and later | |
| SQLite | 3.8.3 and later | |
| SQL Server | 2005 and later | Previous statement must end with `;` |
| Oracle | 9.2 and later | Column aliases recommended |
If your server is older than the version listed, the WITH keyword produces a syntax error, and a derived table is the fallback.
Summary of the working model
A WITH clause defines one or more names, each bound to a SELECT. The main statement follows and can read those names like tables. The names last for that statement only. The columns come from the SELECT list or from an explicit column list. The name can be used several times, and the engine decides how to execute it.
Exercise
Rewrite this query with a CTE named recentorders. It should return the same rows. SELECT c.name, r.amount FROM customers c JOIN ( SELECT customerid, amount FROM orders WHERE orderdate >= '2026-03-01' ) r ON r.customerid = c.id;
Show answer
WITH recentorders AS ( SELECT customerid, amount FROM orders WHERE orderdate >= '2026-03-01' ) SELECT c.name, r.amount FROM customers c JOIN recentorders r ON r.customer_id = c.id; The subquery moves to the top unchanged, and the join refers to the CTE name. With the sample data, the result has three rows: Ben 300.00, Chen 1000.00, and Chen 1200.00.
Exercise
Using order_totals from this chapter, write a query that lists every customer, including those with no orders, and shows 0 instead of NULL for the total. Which join type do you need, and which function replaces NULL?
Show answer
You need a LEFT JOIN from customers to the CTE, so that Dara is kept, and COALESCE to replace NULL: WITH ordertotals AS ( SELECT customerid, SUM(amount) AS total FROM orders GROUP BY customerid ) SELECT c.name, COALESCE(t.total, 0) AS total FROM customers c LEFT JOIN ordertotals t ON t.customerid = c.id ORDER BY c.name; An inner JOIN would drop Dara because she has no row in ordertotals.
Exercise
A colleague's query fails on SQL Server with a syntax error near WITH. The line just before it is SET NOCOUNT ON without a semicolon. What is the fix, and why does it work?
Show answer
Add a semicolon after SET NOCOUNT ON (or write ;WITH). SQL Server reads WITH as a table hint unless the previous statement is terminated, so the semicolon tells the parser that a new statement, a CTE, is starting.