Sub topic 1
A Quick Refresher on WITH and Common Table Expressions
Recursive queries are built on ordinary common table expressions (CTEs). This chapter covers the non-recursive form: how a CTE is written, how it is scoped, how it differs from a subquery or view, and which mistakes come up most. The later chapters add one feature, a CTE that refers to itself.
Prerequisites
This chapter assumes you can already:
- Write
SELECTqueries withWHEREandORDER BY. - Join tables, including a table joined to itself.
- Use
GROUP BYwith aggregates such asSUM,COUNT, andAVG. - Read a basic subquery, such as
WHERE x IN (SELECT ...)or a derived table inFROM.
The examples use standard SQL that runs on PostgreSQL, MySQL 8.0 or later, SQLite 3.8.3 or later, and SQL Server. Dialect differences are noted where they matter.
What a CTE is
A common table expression is a named, temporary result set that exists for the duration of one statement. You define it with WITH, give it a name, and then use that name in the main query as if it were a table.
A CTE is not stored in the database. It is not a table or a view, and it disappears when the statement finishes. Its purpose is to give a name to an intermediate step so the query reads top to bottom.
Basic syntax
The examples in this chapter use a small orders table. Run this setup first:
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL,
order_date DATE NOT NULL,
total NUMERIC(10,2) NOT NULL
);
INSERT INTO orders (id, customer_id, order_date, total) VALUES
(1, 10, '2026-01-05', 120.00),
(2, 10, '2026-02-11', 150.00),
(3, 20, '2026-02-12', 80.00),
(4, 30, '2026-03-01', 300.00),
(5, 20, '2026-03-15', 60.00);The next query finds customers who have spent more than 200 in total:
WITH customer_totals AS (
SELECT customer_id,
SUM(total) AS spent,
COUNT(*) AS order_count
FROM orders
GROUP BY customer_id
)
SELECT customer_id, spent
FROM customer_totals
WHERE spent > 200
ORDER BY spent DESC;The result is customer 30 with 300.00, then customer 10 with 270.00. The aggregation is written once, named, and filtered afterward. Without the CTE you would need a derived table in FROM or a HAVING clause.
A CTE has three parts: the name, an optional column list, and the query in parentheses. The main statement follows the whole WITH clause.
Naming the columns
You can list column names right after the CTE name. The list renames the columns the inner query returns:
WITH t(a, b) AS (
SELECT 1, 2
)
SELECT a + b AS total FROM t;The number of names must match the number of columns the inner query returns. A mismatch is an error. Without a list, the column names come from the inner query, so expressions such as SUM(total) need an alias.
Recursive CTEs often use an explicit column list, because the column names must be known before the recursive part is analyzed. Some dialects require it. Get used to it now.
Chaining several CTEs
Separate multiple CTEs with commas and write WITH only once. A later CTE can read any CTE defined above it:
WITH customer_totals AS (
SELECT customer_id, SUM(total) AS spent
FROM orders
GROUP BY customer_id
),
avg_spend AS (
SELECT AVG(spent) AS avg_spent
FROM customer_totals
)
SELECT c.customer_id, c.spent
FROM customer_totals c
CROSS JOIN avg_spend a
WHERE c.spent > a.avg_spent
ORDER BY c.spent DESC;The average spend is about 236.67, so the query returns customers 30 and 10. Each step builds on the previous one, much like a pipeline.
Scope rules
- A CTE is visible only to the statement that defines it. A second statement cannot use it.
- A CTE can be used in the main query and in CTEs defined after it. It cannot be used by CTEs defined before it, except in recursion, which gets its own chapter.
- Names must be unique within one
WITHclause. - A CTE name hides a real table of the same name inside that statement. This is legal but confusing, so avoid it.
- A CTE can be referenced more than once in the main query, for example in a self-join.
CTE, subquery, view, or temporary table
| Feature | Lifetime | Reusable within the statement | Can refer to itself |
|---|---|---|---|
| Subquery or derived table | One place in one statement | No, it must be repeated | No |
| CTE | One statement | Yes, by name | Yes, if declared recursive |
| View | Stored until dropped | Yes, in any statement | Not directly |
| Temporary table | Session, or until dropped | Yes, in many statements | No |
The last column is why this tutorial uses CTEs. Neither a derived table nor a view can express "repeat this step until nothing new appears", but a recursive CTE can.
Materialization and inlining
A CTE is a logical construct. The database may run it in two ways:
- Inlined: the optimizer merges the CTE into the outer query, as it would a subquery. Filters in the outer query can then be pushed down into it.
- Materialized: the CTE result is computed once and held in a temporary structure. Later references read the stored rows.
Engines differ:
- PostgreSQL 12 and later inlines a CTE that is non-recursive, has no side effects, and is referenced once. Otherwise it materializes the CTE. Earlier versions always materialized. You can force a choice:
WITH customer_totals AS MATERIALIZED (
SELECT customer_id, SUM(total) AS spent
FROM orders
GROUP BY customer_id
)
SELECT * FROM customer_totals WHERE spent > 200;Use NOT MATERIALIZED for the opposite. SQLite 3.35 and later accepts the same hints.
- SQL Server treats a CTE like an inline view and does not materialize it. If a CTE is referenced twice, its query can run twice.
- MySQL 8.0 merges a CTE into the outer query when it can, and otherwise materializes it.
A recursive CTE is always evaluated iteratively, so these choices do not apply to it. The chapter on evaluation covers that.
Common errors
- Using the CTE in a later statement. Running
SELECT * FROM customer_totals;after the query above fails with "table does not exist". The CTE is gone once its statement ends. - Forgetting the semicolon in SQL Server.
WITHcan start a CTE only if the previous statement ended with;. Otherwise SQL Server reads it as a table hint and reports a syntax error. Many people write;WITHfor this reason. - Column count mismatch.
WITH t(a, b) AS (SELECT 1)fails because the list has two names and the query returns one column. - Missing aliases. An unnamed expression in a CTE has no usable column name in some engines, and in others the name is engine-generated. Always alias expressions.
- Using
ORDER BYinside a CTE. Some engines reject it (SQL Server withoutTOP). Where it is accepted, the order is not guaranteed to survive into the outer query. Sort in the outermostSELECT. - Putting
WITHin the wrong place. TheWITHclause comes before the statement that uses it, whether that isSELECT,INSERT,UPDATE, orDELETE. Support forWITHbefore data-changing statements varies by engine. PostgreSQL also allows data-changing statements inside a CTE. - Assuming a CTE caches its result. Whether a CTE runs once or several times depends on the engine and version, as described above. Do not rely on either behavior for correctness. Rely on it only for performance, and check the query plan.
Why this matters for recursion
A recursive CTE has the same overall shape as the examples above: a name, a column list, a parenthesized query, and a main query that reads from the name. It differs in two ways:
- The keyword
RECURSIVEfollowsWITHin PostgreSQL, MySQL, and SQLite. SQL Server omits it. - The parenthesized query has two parts joined by
UNION ALL, and the second part reads from the CTE's own name.
Everything you learned here about naming, column lists, scope, and chaining carries over. The next chapter takes the recursive structure apart piece by piece.
Exercise
Write a query on the orders table using two chained CTEs. The first, monthly, returns each month's total sales and the second, best, returns the single highest monthly total. The final SELECT must show only the month with that highest total. Use the setup data above, and say which function you would use to extract the month in your dialect.
Show answer
One portable version groups by a month string. In SQLite use strftime('%Y-%m', orderdate), in PostgreSQL use tochar(orderdate, 'YYYY-MM'), in MySQL use DATEFORMAT(orderdate, '%Y-%m'), and in SQL Server use FORMAT(orderdate, 'yyyy-MM'). In SQLite: WITH monthly AS ( SELECT strftime('%Y-%m', orderdate) AS month, SUM(total) AS sales FROM orders GROUP BY strftime('%Y-%m', orderdate) ), best AS ( SELECT MAX(sales) AS topsales FROM monthly ) SELECT m.month, m.sales FROM monthly m JOIN best b ON m.sales = b.topsales; With the sample data the months total 2026-01: 120, 2026-02: 230, 2026-03: 360, so the query returns 2026-03 with 360.
Exercise
A colleague runs this in SQL Server and gets a syntax error near WITH: "SELECT 1 WITH c AS (SELECT 2 AS x) SELECT x FROM c". Explain the cause and give the fix.
Show answer
The previous statement, SELECT 1, was not terminated with a semicolon. SQL Server then cannot tell that WITH starts a CTE. End the first statement with a semicolon, or write ";WITH c AS (SELECT 2 AS x) SELECT x FROM c".