🎓 A1Learner
🔍
0 of 51 lessons completed

SQL Recursive CTEs

A recursive CTE builds its rows one step at a time. It starts with a first row, then each step makes the next row from the one before it.

Counting from 1 to 5

Trace it: the first row is 1, the next is 2, then 3, then 4. The stop test ends the steps at 5.

WITH RECURSIVE numbers(n) AS (SELECT 1 UNION ALL SELECT n + 1 FROM numbers WHERE n < 5)
SELECT n FROM numbers
ORDER BY n;

Squares of the same numbers

Five rows come back, each number beside its square: 1, 4, 9, 16 and 25.

WITH RECURSIVE numbers(n) AS (SELECT 1 UNION ALL SELECT n + 1 FROM numbers WHERE n < 5)
SELECT n, n * n AS squared FROM numbers
ORDER BY n;

Counting down instead

Trace it the other way: 5, then 4, then 3, then 2, then 1.

WITH RECURSIVE countdown(n) AS (SELECT 5 UNION ALL SELECT n - 1 FROM countdown WHERE n > 1)
SELECT n FROM countdown
ORDER BY n DESC;

Example

WITH RECURSIVE numbers(n) AS (SELECT 1 UNION ALL SELECT n + 1 FROM numbers WHERE n < 5)
SELECT COUNT(*) AS how_many, SUM(n) AS total FROM numbers;

Key points

  • WITH RECURSIVE: the words that open a CTE that reads itself
  • Anchor: the first row, written as a plain SELECT
  • UNION ALL: the word that joins the first row to the rows each step makes
  • Stop test: the WHERE test that ends the steps
  • Each step reads the rows the CTE has made so far.

In this example, the CTE builds the numbers 1 through 5. The main query counts those rows and adds them up. Five rows give a total of 15.

Note

without a stop test, the steps would never end.

Try it Yourself

Edit the code, then press Run.

Running is simulated · DB Fiddle

Exercise

What does the anchor do in a recursive CTE?