Sub topic 10
CTEs as named, readable subqueries
This chapter assumes you can write SELECT queries with WHERE and GROUP BY, join tables, and handle NULL. It also assumes you have seen a derived table (a subquery in FROM) from the previous chapter. Here you will name that subquery, move it above the main query, and learn where the name stops working.
What a CTE is
A common table expression (CTE) is a named subquery defined at the top of a statement with the WITH keyword. You then use its name in the main query as if it were a table. The name and its rows exist only for that one statement.
Here is the derived-table query from the last chapter rewritten as a CTE:
WITH dept_avg AS (
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
)
SELECT e.name, e.salary, da.avg_salary
FROM employees e
JOIN dept_avg da ON da.department_id = e.department_id
WHERE e.salary > da.avg_salary;The query reads in two steps. First it computes the average salary per department and calls the result dept_avg. Then it joins each employee to their department's average and keeps those paid above it. The logic is the same as with a derived table. Only the layout changes: the building block comes first, and the question it answers comes last.
The general shape is:
WITH name AS (
SELECT ...
)
SELECT ...
FROM name;Why use a CTE instead of a nested subquery
A deeply nested query forces the reader to start in the middle and work outward. A CTE lets them read top to bottom. CTEs help in three ways:
- Naming.
dept_avgtells the reader what the intermediate result means. An anonymous(SELECT ... ) AS sdoes not. - Order. Steps appear in the order you think about them.
- Reuse. You can refer to the same CTE more than once in the statement without copying its text.
A CTE does not give you new abilities for ordinary queries. Anything you can write with a CTE you can also write with derived tables. The benefit is readability, plus recursion (covered at the end).
Chaining several CTEs
You can define more than one CTE after a single WITH. Separate them with commas and write WITH only once. A CTE may use any CTE defined before it in the list.
WITH dept_avg AS (
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
),
above_avg AS (
SELECT e.department_id, COUNT(*) AS n
FROM employees e
JOIN dept_avg da ON da.department_id = e.department_id
WHERE e.salary > da.avg_salary
GROUP BY e.department_id
)
SELECT d.name, a.n AS employees_above_average
FROM departments d
JOIN above_avg a ON a.department_id = d.id
ORDER BY a.n DESC;Each step does one job. dept_avg computes averages. above_avg uses them to count the employees paid above their department's average. The final query attaches department names. Each part can be tested alone by replacing the final SELECT with SELECT * FROM dept_avg.
Scope: where a CTE name is visible
A CTE name works only inside the statement that defines it. It is not a view and it is not saved. Once the statement ends, the name is gone.
Within the statement, these rules apply:
- A CTE can refer to CTEs defined earlier in the same
WITHlist. - A CTE cannot refer to a CTE defined later in the list. Reorder them.
- A CTE cannot refer to itself unless it is a recursive CTE (see the last section).
- The main query can use any CTE from the list.
If a CTE has the same name as a real table, the CTE wins inside the statement. This can confuse readers, so give CTEs names that do not clash with your tables.
Naming the columns
The columns of a CTE take their names from its SELECT list. Use an alias for any computed column, as AS avg_salary does above. You can also list the column names after the CTE name:
WITH dept_avg (department_id, avg_salary) AS (
SELECT department_id, AVG(salary)
FROM employees
GROUP BY department_id
)
SELECT department_id, avg_salary
FROM dept_avg;The names in the list replace the names inside, matched by position. The count must match the number of columns the inner SELECT returns, or the database raises an error. The list form is helpful when the inner query returns unnamed expressions.
Referencing a CTE more than once
A derived table is written at the point of use, so using it twice means pasting it twice. A CTE is written once and referenced as often as you like:
WITH dept_avg AS (
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
)
SELECT department_id, avg_salary
FROM dept_avg
WHERE avg_salary > (SELECT AVG(avg_salary) FROM dept_avg);This returns departments whose average salary is above the mean of all the department averages. The outer query and the scalar subquery both read dept_avg. If the logic for dept_avg changes, you edit one place.
CTEs and performance
A CTE is a way to write a query. It is not automatically a stored intermediate result. What the database does with it depends on the product and version.
| Database | Default behavior for a CTE used once | Control |
|---|---|---|
| PostgreSQL 12 and later | Inlined into the main query like a derived table | `AS MATERIALIZED` or `AS NOT MATERIALIZED` |
| PostgreSQL 11 and earlier | Always computed separately and stored | None |
| SQL Server | Inlined, then optimized as part of the whole query | None; the CTE text is expanded each time it is referenced |
| MySQL 8 | Treated like a derived table; may be merged or materialized | Optimizer settings |
Two consequences follow:
- Do not assume that a CTE is computed once. In SQL Server, a CTE referenced twice may do its work twice.
- Do not assume that a CTE is faster than the equivalent derived table. Usually the plan is the same. Check with the query plan, which a later chapter covers.
PostgreSQL lets you force the choice:
WITH dept_avg AS MATERIALIZED (
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
)
SELECT e.name, e.salary, da.avg_salary
FROM employees e
JOIN dept_avg da ON da.department_id = e.department_id
WHERE e.salary > da.avg_salary;MATERIALIZED computes the CTE once and keeps the result. This helps when the CTE is expensive and referenced several times. It can also hurt, because the planner can no longer push filters from the main query into the CTE. NOT MATERIALIZED asks for inlining.
CTEs with UPDATE and DELETE
In PostgreSQL, SQL Server, SQLite, and MySQL 8, WITH can come before a data-modifying statement. The CTE then names the rows you want to act on:
WITH closed AS (
SELECT id
FROM customers
WHERE status = 'closed'
)
DELETE FROM orders
WHERE customer_id IN (SELECT id FROM closed);This does the same thing as the DELETE with an inline subquery from the earlier chapter. The named version is easier to run as a SELECT first: replace the DELETE with SELECT * FROM orders WHERE customer_id IN (SELECT id FROM closed) to preview the rows. Oracle does not allow WITH before DELETE in this way, so check your product's syntax.
Common errors
- Forgetting the comma between CTEs. Writing
WITH a AS (...) b AS (...)is a syntax error. UseWITH a AS (...), b AS (...). - Repeating WITH. Write
WITHonce, not before each CTE. - Referencing a later CTE. A CTE sees only the ones above it.
- A statement before WITH. In SQL Server, if
WITHis not the first statement in a batch, the previous statement must end with a semicolon. - Missing alias on a computed column.
SELECT AVG(salary)without an alias gives a column with no usable name, unless you supply a column list. - Using a CTE name in a second statement. The name works for one statement only. To reuse it across statements, create a view or a temporary table.
- ORDER BY inside a CTE. Most databases ignore it or reject it unless it is paired with
LIMITorTOP. Sort in the main query.
Recursive CTEs
A CTE marked recursive can refer to itself. It has an anchor part that produces the starting rows, a UNION ALL, and a recursive part that builds on the rows found so far. The database repeats the recursive part until it returns no new rows.
WITH RECURSIVE counter (n) AS (
SELECT 1
UNION ALL
SELECT n + 1
FROM counter
WHERE n < 5
)
SELECT n
FROM counter;This returns the numbers 1 through 5. The WHERE n < 5 is the stopping condition. Without it, the query would run until the database stops it. In SQL Server, leave out the word RECURSIVE. The usual real-world use is walking a hierarchy, such as an employee-and-manager tree. That topic needs a chapter of its own, so this one stops here.
When to choose a CTE
Use a CTE when the query has more than one logical step, when you need the same intermediate result twice, or when a nested subquery has become hard to follow. Keep a plain subquery when the inner query is short and used once, such as salary > (SELECT AVG(salary) FROM employees). A CTE there adds lines without adding clarity.
Exercise
A colleague writes WITH a AS (SELECT id FROM customers) b AS (SELECT customer_id FROM orders) SELECT * FROM a JOIN b ON b.customer_id = a.id; and gets a syntax error. Fix the query, and explain whether CTE a could be made to use CTE b instead.
Show answer
The two CTEs need a comma between them: WITH a AS (SELECT id FROM customers), b AS (SELECT customer_id FROM orders) SELECT * FROM a JOIN b ON b.customer_id = a.id;. A CTE can use only CTEs defined before it in the list. So b could refer to a, but a could not refer to b unless the two were swapped in order.
Exercise
You write a CTE named dept_avg and run a query that uses it. In the next statement, you run SELECT * FROM dept_avg; and get an error that the table does not exist. Why, and what are two ways to keep the result available across statements?
Show answer
A CTE exists only for the single statement that defines it, so the name is gone afterward. To keep the result, create a view (CREATE VIEW dept_avg AS ...) so the query is stored under a name, or create a temporary table (CREATE TEMPORARY TABLE ... AS SELECT ...) so the rows themselves are stored for the session.