Sub topic 1
A quick refresher on WITH and common table expressions
Prerequisites
This chapter assumes you already know SELECT, WHERE, and ORDER BY, INNER JOIN and self-joins, GROUP BY with aggregate functions, and basic subqueries.
Common table expressions
A common table expression (CTE) is a named result set defined in a WITH clause before the main query. The name exists only for the duration of that one statement.
WITH high_paid AS (
SELECT id, name, salary
FROM employees
WHERE salary > 100000
)
SELECT name
FROM high_paid
ORDER BY name;A CTE reads more clearly than a nested subquery, and the same name can be referenced more than once in the main query.
Anatomy of a recursive CTE
A recursive CTE adds the RECURSIVE keyword and has two members joined by UNION ALL:
- The anchor member is a query that runs once and produces the starting rows.
- The recursive member refers to the CTE's own name, so it reads the rows produced by the previous step.
How the database evaluates a recursive CTE
The database uses a working table to run the recursion:
- It runs the anchor member and stores its rows in the working table and the result.
- It runs the recursive member against the working table and stores the new rows.
- It replaces the working table with those new rows and repeats step 2.
- It stops when the recursive member returns no rows, then returns the accumulated result.
Your first recursive query: generating a series
The following query produces the numbers 1 through 10:
WITH RECURSIVE n(i) AS (
SELECT 1
UNION ALL
SELECT i + 1 FROM n WHERE i < 10
)
SELECT i FROM n;The anchor SELECT 1 seeds the working table with one row. Each iteration adds 1 to the previous value. The condition WHERE i < 10 stops the recursion after the value 10 is produced.
Exercise
Exercise
In the series query above, what happens if you remove the WHERE i < 10 condition?
Show answer
The recursive member always returns a row, so the recursion never ends. PostgreSQL, MySQL, and SQLite stop with an error or run until a resource limit is hit. SQL Server stops at its default limit of 100 levels.