# Recursive CTEs

> Walk a tree such as an org chart with WITH RECURSIVE, see the working table fill round by round, and stop loops safely.

Subject: SQL | Lesson 26 of 44 | 7 min read
Interactive lesson: https://codewithanimation.in/sql/recursive-ctes
Previous: [Common Table Expressions (WITH)](https://codewithanimation.in/sql/common-table-expressions.md) | Next: [Window Functions](https://codewithanimation.in/sql/window-functions.md)

## A CTE that uses itself

A **recursive CTE** refers to its own result. It has two parts joined by `UNION ALL`: a starting part that runs once, and a recursive part that runs again and again on the rows found in the previous round.

You write `WITH RECURSIVE`. The database keeps a **working table** with the rows of the latest round. It repeats the recursive part against that table until a round produces no new rows, then stops.

## Trees and chains of any depth

Org charts, folders inside folders, category trees and comment replies all have a depth that nobody knows in advance. A normal join needs one join per level. A recursive CTE follows the chain however long it is.

## Walk the org chart from the top

```sql
WITH RECURSIVE tree(id, name, depth) AS (
  SELECT id, name, 0 FROM staff WHERE id = 1
  UNION ALL
  SELECT s.id, s.name, tree.depth + 1
  FROM staff s JOIN tree ON s.manager_id = tree.id
)
SELECT * FROM tree;
```

Round 0 finds Asha, the starting row, at depth 0. Round 1 finds the people who report to Asha: Ben and Chen, depth 1. Round 2 finds who reports to them: Dara and Eli, depth 2. Round 3 finds nobody, the working table is empty, and the query stops with 5 rows.

The classic first example is counting: `SELECT 1 UNION ALL SELECT n + 1 FROM t WHERE n < 5` produces 1, 2, 3, 4, 5. The `WHERE n < 5` is what stops it.

## Common mistake: Loops never stop by themselves

If the data loops back, for example Asha reports to Eli, who reports to Ben, who reports to Asha, the working table is never empty. The query runs until the server runs out of memory or the statement is cancelled.

Two ways to stop it. Put a condition in the recursive part, such as a depth limit. Or use the `CYCLE` clause, which adds an `is_cycle` column and does not follow a row once its key has already appeared on the same path.

Changing `UNION ALL` to `UNION` removes duplicate rows and can stop some loops, but not when you also keep a `depth` column, because every round then makes new, different rows.

## Tip: Write the stop first

Before you write the recursive part, decide what makes it stop: a count, a depth, or no more matching rows. Test on a small table, and add `CYCLE` when the data might contain loops.

## Try it: Run it one round at a time

Press Next round and watch the working table and the result grow. Then try the loop modes to see what happens with no guard and with CYCLE.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/sql/recursive-ctes

## Check yourself

### Question 1

When does a recursive CTE stop?

- A. When a round of the recursive part produces no new rows
- B. After exactly 100 rounds
- C. When the starting part finishes

Correct answer: A

The recursive part is repeated against the working table until it finds nothing new, which leaves the working table empty.

- Why not B: There is no built-in limit. A loop would carry on until something else stops it.
- Why not C: The starting part runs only once. The recursion is the repeated part.

### Question 2

The org chart walk starts at Asha (depth 0). Who is found in round 1?

- A. Ben and Chen, who report to Asha
- B. Dara and Eli, who report to Ben
- C. Everyone at once

Correct answer: A

Round 1 joins the working table (Asha) to the people whose manager_id is Asha's id: Ben and Chen.

- Why not B: They are found one round later, in round 2.
- Why not C: Each round only follows one more level down.

### Question 3

The reporting data contains a loop (Asha reports to Eli, and Eli is below Asha). What happens to a recursive CTE with no guard?

- A. It never ends, because the working table never becomes empty
- B. It ends after one trip around the loop
- C. It returns an error right away

Correct answer: A

Each round finds new rows around the loop, so there is always something to process. Use CYCLE or a depth limit.

- Why not B: Nothing detects the repeat unless you add a guard such as CYCLE.
- Why not C: PostgreSQL cannot tell in advance. It simply keeps running.

## Remember this

- A recursive CTE is a starting part plus a recursive part, joined by UNION ALL.
- Each round runs the recursive part on the rows of the previous round (the working table).
- It stops when a round finds no new rows.
- Data that loops makes the query run forever, so add a stop: a depth limit or CYCLE.
