Before continuing: This entry is part of the CTE guide. If you are new to the topic, start with WITH and CTE.
Examples
We want to add up the shipped order amounts per customer and then show the customer's name. First we build the summary by customer_id and then join it to customers.
SELECT c.name, r.total_shipped
FROM customers AS c
JOIN (
SELECT customer_id,
ROUND(SUM(total), 2) AS total_shipped
FROM orders
WHERE status = 'shipped'
GROUP BY customer_id
) AS r ON r.customer_id = c.id
ORDER BY r.total_shipped DESC, c.name;WITH shipped_per_customer AS (
SELECT customer_id,
ROUND(SUM(total), 2) AS total_shipped
FROM orders
WHERE status = 'shipped'
GROUP BY customer_id
)
SELECT c.name, e.total_shipped
FROM customers AS c
JOIN shipped_per_customer AS e
ON e.customer_id = c.id
ORDER BY e.total_shipped DESC, c.name;Both queries return the same seven rows on the teaching database. The difference is how the intermediate result is written: as a derived table inside JOIN or as a named CTE at the start.
Differences and trade-offs
Quick comparison
| Criterion | Subquery | CTE |
|---|---|---|
| Where it is defined | Inside another part of the query | At the start, with WITH |
| Has its own name | Only when it acts as a derived table with an alias | Yes, the name identifies the intermediate result |
| Reading step by step | Handy when the step is short and local | Handy when you want clearly named stages |
| Multiple references | A given derived table is referenced where it appears | A CTE can be referenced several times within the statement, subject to the engine's rules |
| Recursion | Not its normal use | Recursive CTEs have specific syntax and rules |
| Performance | There is no universal winner: the optimiser and the specific query matter | |
When to choose a subquery
- The step is short and only matters in one place. Keeping it next to the
JOIN, filter or expression avoids jumping around while reading. - You need a scalar expression. For example,
price > (SELECT AVG(price) FROM products)expresses a comparison against a single value directly. - The question is about existence. A subquery correlated with
EXISTSusually says “is there a related row?” more clearly.
A subquery is not worse just because it is nested. The problem appears when you pile up several levels, repeat the same logic or force the reader to rebuild too many dependencies at once.
When to choose a CTE
- You want to give a stage a name.
shipped_per_customerexplains what the result contains before the main query uses it. - The statement has several stages. Several comma-separated CTEs can turn a long query into a readable sequence.
- You need to refer to the same named result more than once. The CTE provides that name within the statement, although how it is executed depends on the engine.
- You need recursion. Hierarchies and recursive walks need a recursive CTE on the engines that support it.
A CTE only exists for the statement that uses it. It does not replace a view, a temporary table or a permanent table when you need to keep or reuse results across statements.
Do not choose based on the “CTEs are faster” myth
There is no reliable rule saying a CTE is always faster than a subquery, or the other way round. Optimisers may inline, materialise or re-run intermediate results depending on the engine, the version and the shape of the query.
- PostgreSQL: a non-recursive CTE with no side effects can be folded into the main query in some cases; it also offers
MATERIALIZEDandNOT MATERIALIZED. - MySQL 8.4: documents that CTEs and derived tables can be interchangeable in simple cases, and that optimisation may involve merging or materialising them.
- SQLite: describes ordinary CTEs as a way of factoring out subqueries and leaves strategy to the planner unless you give explicit materialisation hints.
- SQL Server: a CTE defines a named result within a single statement, and its documentation notes that references to it do not imply a persisted, materialised result.
If performance matters, compare plans and timings with representative data on your engine. Readability is a valid reason to choose one form; an assumed automatic speed advantage is not.