Sub topic 11
Common mistakes and when not to use a CTE
This chapter assumes you can write a basic CTE with WITH, chain several CTEs, and read a recursive CTE with an anchor member and a recursive member. It covers the errors that show up most in practice, then the cases where another tool fits better. Examples use PostgreSQL unless a note says otherwise.
Mistakes with scope
A CTE name exists only for the single statement that follows the WITH clause. It is not a view and it is not a temporary table.
WITH big_orders AS (
SELECT id, amount FROM orders WHERE amount > 500
)
SELECT COUNT(*) FROM big_orders;
-- A separate statement: big_orders no longer exists here.
SELECT COUNT(*) FROM big_orders;
-- ERROR: relation "big_orders" does not existIf you need the same intermediate result in several statements, a CTE makes you repeat its definition each time. Later sections cover better options.
Two related scope errors are common:
- Referencing a later CTE from an earlier one. In a non-recursive
WITHlist, a CTE can see only the CTEs defined above it. Reorder the list so that dependencies come first. - Forgetting the comma between CTEs. Write
WITHonce, then separate the CTEs with commas. A secondWITHkeyword in the same list is a syntax error.
In SQL Server, the statement before a WITH clause must end with a semicolon. Otherwise the parser reads WITH as a table hint. Many teams write ;WITH for that reason, but ending every statement with a semicolon is cleaner.
Mistakes about execution
Assuming a CTE is a performance boundary
Readers often believe that a CTE is computed first, stored, and then read by the outer query. Whether that happens depends on the engine and its version.
| Engine | Typical behavior for a non-recursive CTE |
|---|---|
| PostgreSQL 12 and later | Inlined if referenced once and free of side effects. Materialized if referenced more than once, unless you add a keyword. |
| PostgreSQL 11 and earlier | Always materialized, so filters in the outer query are not pushed down. |
| SQL Server | Treated like a view. The definition is expanded into each place it is used. There is no materialization hint. |
| MySQL 8 and MariaDB | The optimizer chooses between merging the CTE into the outer query and materializing it. |
Because of this, two mistakes follow. The first is adding a CTE to "force" an early filter. The second is assuming a CTE referenced three times is computed once. In SQL Server, it may be computed three times.
In PostgreSQL 12 and later, you can state your intent:
WITH recent AS NOT MATERIALIZED (
SELECT * FROM orders WHERE order_date >= DATE '2026-01-01'
)
SELECT * FROM recent WHERE customer_id = 42;With NOT MATERIALIZED, the planner can combine both conditions and use an index on customer_id. With MATERIALIZED, it would first build every recent order and then filter that result. Use MATERIALIZED when the CTE is expensive and referenced several times, or when you want to stop the planner from choosing a bad plan. Check the real behavior with EXPLAIN instead of guessing.
Relying on ORDER BY inside a CTE
A CTE is a set of rows, and sets have no order. This query gives no guarantee about the order of the final output:
WITH sorted AS (
SELECT id, amount FROM orders ORDER BY amount DESC
)
SELECT id, amount FROM sorted;SQL Server rejects an ORDER BY inside a CTE unless you also use TOP or OFFSET. Other engines accept it and may ignore it. Put ORDER BY in the outermost query. The exception is a CTE that needs an order for a purpose such as LIMIT, where the order picks which rows are kept.
Expecting a CTE to run when nothing uses it
In PostgreSQL, a SELECT CTE that is never referenced is not executed. A data-modifying CTE is different. It always runs to completion, even if nothing reads its RETURNING output. All sub-statements in one data-modifying WITH also see the same snapshot of the data, so one UPDATE cannot see another's changes. The only way to pass changes between them is RETURNING. The order in which sibling data-modifying CTEs execute is not specified.
Mistakes in recursive CTEs
No safe stopping rule
A recursive member keeps running until it produces no new rows. If the data contains a cycle, such as an employee whose management chain loops back to themselves, the recursion never ends. The engine runs until it hits a limit or exhausts memory or disk.
A depth limit is the simplest guard:
WITH RECURSIVE walk AS (
SELECT 1 AS id, 0 AS depth
UNION ALL
SELECT e.to_id, w.depth + 1
FROM walk w
JOIN edges e ON e.from_id = w.id
WHERE w.depth < 10
)
SELECT id, depth FROM walk;This bounds the work, but on a cyclic graph it still returns the same node repeatedly, once per lap. A path array, shown earlier in the tutorial, prevents revisits:
WITH RECURSIVE walk AS (
SELECT 1 AS id, ARRAY[1] AS path
UNION ALL
SELECT e.to_id, w.path || e.to_id
FROM walk w
JOIN edges e ON e.from_id = w.id
WHERE e.to_id <> ALL (w.path)
)
SELECT id, path FROM walk;Use both guards when the data comes from outside your control. Many engines also have a configurable recursion cap, such as MAXRECURSION in SQL Server, which defaults to 100 and raises an error when exceeded. That setting is a safety net, not a design.
Putting the stop condition in the wrong place
The condition belongs in the WHERE clause of the recursive member. A filter in the outer query runs after the recursion has finished, so it limits output but not work. Compare these two:
-- Stops generating rows at 5
WITH RECURSIVE numbers(n) AS (
SELECT 1
UNION ALL
SELECT n + 1 FROM numbers WHERE n < 5
)
SELECT n FROM numbers;If you remove WHERE n < 5 and put WHERE n <= 5 only in the final SELECT, the recursion never terminates in engines that do not stop early. PostgreSQL stops early only when the outer query has a LIMIT. Do not depend on that.
Mismatched column types
The anchor member decides the type of each column. The recursive member must produce compatible values. A text column that starts as varchar(1) and grows with each step does not fit. PostgreSQL reports that the column has one type in the non-recursive term and a different type overall. SQL Server requires exact type matches between the anchor and the recursive part. Cast the anchor to the widest type you need:
WITH RECURSIVE chain(n, label) AS (
SELECT 1, CAST('a' AS text)
UNION ALL
SELECT n + 1, label || 'b' FROM chain WHERE n < 3
)
SELECT n, label FROM chain;This returns a, ab, and abb. Without the cast, a fixed-length type in the anchor would truncate or reject the longer values.
Using UNION where UNION ALL is meant
UNION removes duplicate rows in each round, which costs a sort or hash. It can also end a cycle, because a repeated row adds nothing new. That only works when the rows are identical. A depth or path column makes each row unique, so UNION no longer stops the loop. Use UNION ALL by default and add an explicit guard.
The RECURSIVE keyword
PostgreSQL and MySQL require WITH RECURSIVE for a recursive CTE. SQL Server and Oracle use plain WITH and detect recursion from the self-reference. Moving a query between these engines is the usual source of "syntax error near WITH".
Mistakes in design
Over-chaining
A pipeline of eight CTEs can read well, or it can hide a simple query behind many names. Signs of trouble are a CTE that only renames columns, a CTE used once whose body is two lines, and many CTEs that each repeat the same join. Name a step when the name explains something that the code does not. If you have to read all eight to follow the logic, the query may need a view or a different approach.
Hiding a join or filter inside a CTE
Putting a filter in a CTE on a column that the outer query also filters can mask a missing index or a join-order problem. When reading a slow query, flatten the CTEs mentally and check whether the plan still makes sense.
Aggregating twice by accident
A common pipeline bug is joining a one-to-many CTE to another table and then summing again, which multiplies the totals:
WITH order_totals AS (
SELECT customer_id, SUM(amount) AS total
FROM orders
GROUP BY customer_id
)
SELECT c.id, SUM(t.total) AS wrong_total
FROM customers c
JOIN order_totals t ON t.customer_id = c.id
JOIN payments p ON p.customer_id = c.id
GROUP BY c.id;order_totals has one row per customer, but each customer has many payments. After the join, each total repeats once per payment, and SUM adds the repeats. Aggregate each many-side table in its own CTE, then join the one-row-per-customer results.
When not to use a CTE
A CTE is a good fit for readability inside one statement. These cases call for something else:
- The same result is needed by many statements. Create a view. The definition lives in one place and every query can use it.
- A large intermediate result is reused and needs an index. A CTE has no indexes of its own, and statistics on it are limited. Use a temporary table:
CREATE TEMPORARY TABLE order_totals AS
SELECT customer_id, SUM(amount) AS total
FROM orders
GROUP BY customer_id;
CREATE INDEX ON order_totals (customer_id);
ANALYZE order_totals;- The step is a simple one-level filter. An inline subquery or a plain
WHEREclause is shorter. - You need row-by-row logic that depends on each outer row. A
LATERALjoin (orCROSS APPLYin SQL Server) fits better than a CTE, because a CTE cannot reference columns from the outer query. - The query must be portable across engines with different recursion syntax. Check the dialect before writing it, or keep the hierarchy logic in application code or a stored column such as a materialized path.
- You want a guaranteed optimization fence. A CTE gives no such guarantee in most engines. If you need one, use a temporary table or the engine's own hint.
Quick diagnosis table
| Symptom | Likely cause | Fix |
|---|---|---|
| `relation does not exist` for a CTE name | Used in a second statement | Repeat the `WITH` clause, or use a view or temporary table |
| Syntax error at `WITH` in SQL Server | Previous statement has no semicolon | End the previous statement with `;` |
| Syntax error at `RECURSIVE` | Engine does not use that keyword | Remove it for SQL Server and Oracle |
| Query never finishes | Cycle or missing stop condition | Add a depth limit and a path check |
| Type or length error in recursion | Anchor column type too narrow | Cast the anchor to the wider type |
| Slow query after adding a CTE | CTE materialized, filter not pushed down | Try `NOT MATERIALIZED`, or check `EXPLAIN` |
| Output order is random | `ORDER BY` placed inside the CTE | Move it to the outer query |
| Totals too large | Join fan-out before a second `SUM` | Aggregate each many-side table separately first |
Exercise
A PostgreSQL 14 query defines a CTE recent_orders once and uses it in a final query that filters on customer_id = 42. The orders table has an index on customer_id, but the query scans every recent order. What setting might explain this, and how do you test it?
Show answer
The CTE may be materialized, which happens by default when a CTE is referenced more than once or when MATERIALIZED is specified. A materialized CTE is built in full before the outer filter applies, so the index on customer_id is not used. Rewrite the CTE as recent_orders AS NOT MATERIALIZED (...), run EXPLAIN (ANALYZE) on both versions, and compare the plans. If the second version uses the index, keep it.
Exercise
This recursive query runs forever on data that contains a cycle. Name two changes that make it safe, and explain why changing UNION ALL to UNION alone would not help.
WITH RECURSIVE walk AS (
SELECT 1 AS id, 0 AS depth
UNION ALL
SELECT e.toid, w.depth + 1
FROM walk w
JOIN edges e ON e.fromid = w.id
)
SELECT id, depth FROM walk;
Show answer
Add WHERE w.depth < N to the recursive member to bound the number of rounds, and track visited ids in a path array, skipping any to_id already in the path. Changing to UNION does not help because each row carries a different depth, so no two rows are identical and no row is ever discarded as a duplicate.
Exercise
Give two situations where a temporary table or a view is a better choice than a CTE.
Show answer
Use a view when many separate statements need the same named result, because a CTE lasts only for one statement. Use a temporary table when a large intermediate result is read several times and needs an index or fresh statistics, because a CTE has neither.