Sub topic 11
Common Mistakes and When Not to Use a CTE
Assume you know SELECT, WHERE, JOIN, GROUP BY, aggregates, and basic subqueries. This chapter focuses on choosing and checking CTEs rather than learning their basic syntax.
A common table expression (CTE) is a named query result created with WITH. It exists only for one SQL statement. CTEs can make a complicated statement easier to read, but they do not automatically make it faster or safer.
Mistake: treating a CTE like a permanent table
A CTE name is visible only inside the statement that follows its WITH clause. It does not create a table, view, or reusable session variable.
WITH recent_orders AS (
SELECT *
FROM orders
WHERE order_date >= DATE '2026-01-01'
)
SELECT COUNT(*) AS order_count
FROM recent_orders;
-- This fails because recent_orders no longer exists:
SELECT * FROM recent_orders;A later CTE can refer to an earlier CTE in the same WITH clause. The reverse is not allowed.
WITH totals AS (
SELECT customer_id, SUM(amount) AS total
FROM orders
GROUP BY customer_id
),
large_totals AS (
SELECT *
FROM totals
WHERE total > 1000
)
SELECT *
FROM large_totals;Keep this dependency direction clear. If two CTEs need each other, you may have a design problem. Recursive CTEs are the special case that allows a CTE to refer to itself.
Mistake: assuming a CTE always improves performance
A CTE is primarily a query-organization tool. Depending on the database and query, the optimizer may inline its query into the surrounding statement or materialize it as an intermediate result.
Materialization means computing and storing the CTE result before continuing. It can avoid repeating an expensive calculation, but it can also require writing and reading a large temporary result. Inlining can allow better filtering and join optimization, but it may repeat work when the CTE is referenced several times.
| Choice | Possible benefit | Possible cost |
|---|---|---|
| Inline the CTE | Filters and joins can be optimized together | An expression might be evaluated repeatedly |
| Materialize the CTE | A shared result can be computed once | A large intermediate result may use memory or disk |
Use an execution plan, such as EXPLAIN, when performance matters. Do not infer performance from the presence of WITH.
Mistake: hiding duplicate rows
A CTE does not remove duplicates. If a join inside the CTE returns several rows for one customer, the outer query receives all of them.
WITH customer_orders AS (
SELECT c.id, c.name, o.id AS order_id
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.id
)
SELECT name, COUNT(*) AS rows_found
FROM customer_orders
GROUP BY id, name;This counts orders, not necessarily distinct business events. If the joins can multiply rows, decide whether you need COUNT(*), COUNT(DISTINCT order_id), or aggregation before the join.
Also check column names. Selecting * from several joined tables can create duplicate or unclear columns. Name the columns that the next CTE actually needs.
Mistake: using recursion without a reliable stop
A recursive CTE has an anchor member and a recursive member. The recursive member must eventually return no rows, or the query can run indefinitely or hit a database limit.
WITH RECURSIVE numbers(n) AS (
SELECT 1
UNION ALL
SELECT n + 1
FROM numbers
WHERE n < 5
)
SELECT n
FROM numbers;For hierarchies, a termination condition such as manager_id IS NULL in the anchor does not protect against cycles in the data. An employee who eventually manages themself can cause repeated traversal. Add a depth limit or track visited identifiers when the database supports that approach.
When a CTE is the wrong tool
Prefer a simpler subquery when the query has one small intermediate expression and naming it does not improve understanding. A CTE can add vertical distance without adding useful structure.
Use a view when the logic is a stable, shared database object that many statements need. Use a temporary table when you need indexes, statistics, or several separate statements to work with the intermediate data. Use a permanent table when the result must persist as stored data.
CTE syntax also differs across database systems. Recursive queries may require WITH RECURSIVE, while some systems use WITH for both recursive and nonrecursive forms. Data-modifying CTEs, MATERIALIZED, and NOT MATERIALIZED are not equally portable. Check your database documentation before moving a query between systems.
Exercise
A CTE is referenced twice, and each reference filters it differently. The CTE produces millions of rows. What should you check before deciding whether to rewrite it?
Show answer
Check the execution plan and the database's materialization or inlining behavior. Compare the cost of computing the shared result once with the cost of filtering and optimizing each use separately.