Recursive CTEs
A recursive CTE in SQL is a common table expression that refers to itself, so its query is repeated until it produces no new rows. It is used to walk chains and trees whose depth isn't known in advance, such as course prerequisites, mentors and managers, or folders inside folders. A self join can follow one level per join; a recursive CTE follows as many levels as there are. In this lesson, we will learn how a recursive CTE works step by step, walk the Fee Tracker's two chains, generate rows, and stop a query that would loop forever.
In One Minute
- A recursive CTE is written
WITH RECURSIVE name AS (anchor UNION ALL recursive_part). - The anchor query runs once and gives the starting rows.
- The recursive part joins to
nameand runs again and again on the rows found last time. - It stops when the recursive part returns no new rows.
- Data with a loop never stops; guard with a depth limit, a path check, or PostgreSQL's
CYCLEclause.
Syntax
WITH RECURSIVE cte_name AS (
anchor_query -- runs once
UNION ALL
recursive_query -- refers to cte_name; runs until it returns nothing
)
SELECT ... FROM cte_name;The two parts must return the same number of columns with compatible types, as in any UNION ALL.
How It Works, Step by Step
Java Collections needs Java OOP, which needs Java Basics. The following query follows that chain backwards from Java Collections:
WITH RECURSIVE chain AS (
SELECT course_id, title, prerequisite_id, 1 AS step
FROM courses
WHERE title = 'Java Collections'
UNION ALL
SELECT c.course_id, c.title, c.prerequisite_id, ch.step + 1
FROM courses AS c
JOIN chain AS ch ON c.course_id = ch.prerequisite_id
)
SELECT step, title
FROM chain
ORDER BY step; step | title
------+------------------
1 | Java Collections
2 | Java OOP
3 | Java Basics
(3 rows)Explanation: The database works in rounds:
| Round | Input (rows found last round) | Recursive part finds | New rows |
|---|---|---|---|
| Anchor | Java Collections (prerequisite 2) | 1 | |
| 1 | Java Collections | course 2, Java OOP (prerequisite 1) | 1 |
| 2 | Java OOP | course 1, Java Basics (prerequisite NULL) | 1 |
| 3 | Java Basics | nothing: no course has id NULL | 0, so stop |
Each round joins only the rows found in the round before, not the whole result. The step column counts the rounds, which is a common way to record depth.
Example: Every Learning Path
Walking the other way, from courses with no prerequisite down to the courses that need them, gives every learning path:
WITH RECURSIVE path AS (
SELECT course_id, title, 1 AS depth, title::text AS route
FROM courses
WHERE prerequisite_id IS NULL
UNION ALL
SELECT c.course_id, c.title, p.depth + 1, p.route || ' → ' || c.title
FROM courses AS c
JOIN path AS p ON c.prerequisite_id = p.course_id
)
SELECT depth, route
FROM path
ORDER BY route; depth | route
-------+-------------------------------------------
1 | Git Basics
1 | Java Basics
2 | Java Basics → Java OOP
3 | Java Basics → Java OOP → Java Collections
1 | JavaScript Basics
1 | SQL Basics
(6 rows)Explanation: The anchor picks the four starting courses. Each round adds the courses whose prerequisite_id points at a course found in the previous round, and extends the route text. Only the Java track goes deeper than one level.
Example: The Mentor Chain
The same pattern walks people. Srihitha mentors Advitha, who mentors Navika:
WITH RECURSIVE mentors AS (
SELECT student_id, first_name, mentor_id, 0 AS level
FROM students
WHERE mentor_id IS NULL
UNION ALL
SELECT s.student_id, s.first_name, s.mentor_id, m.level + 1
FROM students AS s
JOIN mentors AS m ON s.mentor_id = m.student_id
)
SELECT level, first_name
FROM mentors
ORDER BY level; level | first_name
-------+------------
0 | Srihitha
1 | Advitha
2 | Navika
(3 rows)Explanation: The anchor finds the student with no mentor, Srihitha, at level 0. Each round finds the students mentored by someone found in the previous round. Self Join needed one extra join per level; this query works for a chain of any length.
Generating Rows
A recursive CTE can also generate rows that aren't in any table. The following query makes one row for each month from August 2025 to January 2026:
WITH RECURSIVE months AS (
SELECT DATE '2025-08-01' AS month
UNION ALL
SELECT (month + INTERVAL '1 month')::date
FROM months
WHERE month < DATE '2026-01-01'
)
SELECT month
FROM months
ORDER BY month; month
------------
2025-08-01
2025-09-01
2025-10-01
2025-11-01
2025-12-01
2026-01-01
(6 rows)Explanation: The anchor gives August 2025. Each round adds one month, and the WHERE stops the recursion after January 2026. In PostgreSQL, generate_series does the same more simply, but the recursive form works in every database that supports CTEs.
Stopping Infinite Loops
If the data contains a loop, the recursion never runs out of new rows. Suppose someone mistakenly sets Java Basics' prerequisite to Java Collections, closing the circle. PostgreSQL 14 and later can detect this with the CYCLE clause:
UPDATE courses SET prerequisite_id = 3 WHERE course_id = 1;
WITH RECURSIVE chain AS (
SELECT course_id, prerequisite_id FROM courses WHERE course_id = 3
UNION ALL
SELECT c.course_id, c.prerequisite_id
FROM courses AS c
JOIN chain AS ch ON c.course_id = ch.prerequisite_id
) CYCLE course_id SET is_cycle USING path
SELECT course_id, is_cycle, path
FROM chain
ORDER BY array_length(path, 1);UPDATE 1
course_id | is_cycle | path
-----------+----------+-------------------
3 | f | {(3)}
2 | f | {(3),(2)}
1 | f | {(3),(2),(1)}
3 | t | {(3),(2),(1),(3)}
(4 rows)Explanation: CYCLE course_id records the course_id values visited in path. When a round reaches a course already in the path (course 3 again), it marks the row with is_cycle = true and stops following it. Without the clause, this query would run until it ran out of memory or time.
Other databases: SQL Server writes WITH without RECURSIVE and stops at 100 levels by default (OPTION (MAXRECURSION n) changes it); Oracle also has the older CONNECT BY syntax.
Common Mistakes
Forgetting RECURSIVE. In PostgreSQL and MySQL, WITH chain AS (... FROM chain ...) fails because chain doesn't exist yet.
No stopping condition. The recursive part must eventually return nothing: a join that runs out, or a WHERE limit.
UNION instead of UNION ALL by habit. UNION removes duplicates each round, which can hide or prevent loops but costs time; use it only on purpose.
Mismatched columns. The anchor and recursive parts need the same columns and types; cast text columns like title::text when you build strings.
Interview Corner
What is a recursive CTE?
A CTE that references itself. An anchor query gives the starting rows, and a recursive query joined to the CTE runs repeatedly on the latest rows until it returns none.
How do you find all managers above an employee?
A recursive CTE: the anchor selects the employee; the recursive part joins employees to the CTE on employees.id = cte.manager_id, climbing one level per round.
How do you prevent infinite recursion?
Add a depth limit, track visited ids in a path and stop on repeats, or use PostgreSQL's CYCLE clause. SQL Server also limits recursion to 100 levels by default.
Practice
Challenge: List Navika (student 103) and everyone above her in the mentor chain, with a level column that is 0 for Navika, 1 for her mentor, and so on. Sort by level.
Show solution
WITH RECURSIVE up AS (
SELECT student_id, first_name, mentor_id, 0 AS level
FROM students
WHERE student_id = 103
UNION ALL
SELECT s.student_id, s.first_name, s.mentor_id, up.level + 1
FROM students AS s
JOIN up ON s.student_id = up.mentor_id
)
SELECT level, first_name
FROM up
ORDER BY level; level | first_name
-------+------------
0 | Navika
1 | Advitha
2 | Srihitha
(3 rows)The anchor is Navika; each round climbs to the mentor of the previous row. Srihitha has no mentor, so the third round finds nothing and the recursion stops.
Key Takeaways
| You want to | Write |
|---|---|
| Walk up a chain | anchor WHERE id = ..., recursive JOIN cte ON t.id = cte.parent_id |
| Walk down a tree | anchor WHERE parent_id IS NULL, recursive JOIN cte ON t.parent_id = cte.id |
| Track depth | 1 AS depth in the anchor, cte.depth + 1 in the recursive part |
| Catch loops (PostgreSQL 14+) | ) CYCLE id SET is_cycle USING path |
Was this tutorial helpful?