Stop 07 · Subqueries, CTEs & Set OperationsTopics · 7/9

Recursive CTEs

Part of the SQL Roadmap

In short

Org charts, category trees and referral chains can go any number of levels deep. A recursive CTE walks them level by level until there's nothing left to find, with no fixed number of self joins.

A recursive CTE refers to itself to walk hierarchies or generate series, for example an org chart or a list of dates. MySQL supports them from version 8.0.

The jaadu sits beside a grandmother on a courtyard swing holding an old landline phone, with curly phone cords branching out to aunts, uncles and children spread across the courtyard.

Think of it like this

The family phone tree

Before a family wedding, Dadi calls her children with the news. Each child then calls their own children, and they call theirs. The calling stops when someone has no one left to call. A recursive CTE is that phone tree: the anchor is Dadi's first call, and each round finds the next generation from the last one.

Watch it happen

Walking an org chart one level at a time

Priya (CEO)
Arjun
Neha
Vikram
Sana
Kiran
Dev

1/5Anchor: the row with no manager. Level 1.

The big ideas

What you need to know

Anchor member

The first SELECT is the starting point, like the CEO or day 1. It runs once.

Recursive member

The second SELECT joins the table to the CTE itself, finding the next level from the last one.

It must stop

Recursion ends when a round returns no rows. Add a guard like level < 20 against loops in bad data.

Generate series too

Start at 1 and add 1 until 30 to create a row for every day of a month.

How it works

How the database runs it

  1. 1

    Run the anchor

    Find the top of the tree and put it in the working set.

  2. 2

    Run the recursive part

    Join the table to the working set to find the next level.

  3. 3

    Replace the working set

    The new rows become the input for the next round.

  4. 4

    Repeat until empty

    When a round finds no new rows, recursion stops.

  5. 5

    Return everything

    All rounds are combined with UNION ALL into one result.

See it in code

Walk through the code

sql
1WITH RECURSIVE org AS (2  SELECT emp_id, name, manager_id,3         1 AS level,4         name::text AS path5  FROM employees6  WHERE manager_id IS NULL7 8  UNION ALL9 10  SELECT e.emp_id, e.name, e.manager_id,11         org.level + 1,12         org.path || ' > ' || e.name13  FROM employees AS e14  JOIN org ON e.manager_id = org.emp_id15  WHERE org.level < 2016)17SELECT level, name, path18FROM org19ORDER BY path;

1/4Anchor: the person with no manager. Level 1, and the path starts with their name.

The full org chart with each person's level and reporting path. MySQL 8 also uses WITH RECURSIVE, with CAST(name AS CHAR(500)) and CONCAT for the path. SQL Server drops the word RECURSIVE.

Save yourself the pain

Common mistakes

Oops

Forgetting the stopping condition when generating numbers.

Do this instead

WHERE n < 30 in the recursive part. Without it the query runs until it errors or uses all memory.

Oops

Using name in the anchor and name || ' > ' || ... in the recursive part with different types.

Do this instead

Both halves must have matching column types. Cast the anchor, like name::text.

Oops

Using UNION instead of UNION ALL out of habit.

Do this instead

UNION ALL is the normal choice. UNION adds duplicate checks each round and is only needed to stop cycles.

Your mission

Trees and calendars

~30 min

Quick check

When does a recursive CTE stop?

Go deeper

  1. 1Generate the numbers 1 to 30 with a recursive CTE.
  2. 2Walk an employee-manager hierarchy to show each person's level.
  3. 3Always include a stopping condition to avoid infinite loops.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge