Recursive CTE in SQL: WITH RECURSIVE Step by Step

WITH RECURSIVE walks a tree one level at a time: an org chart, a category path, a date series. Every iteration shown, plus the depth limit and cycles.

In this chapter

WITH RECURSIVE keeps joining the rows it just found

Recursive CTEs: common questions

How does a recursive CTE work?

The anchor query returns the first rows. The recursive part joins the rows found in the last step to find the next level, and it repeats until a step returns no rows.

How do I stop infinite recursion?

Add a depth column with a limit such as WHERE depth < 20, or track the visited path and skip rows already in it.

More on WITH and CTEs

Keep learning

Overview

Alice Chen Bob Singh VP Engineering Carol Diaz VP Sales Dana Okonkwo Engineering Manager Eve Patel Frank Rossi Sales Manager Grace Kim Software Engineer Hank Nguyen Iris Berg Jade Alvarez Account Executive Ken Ito The anchor runs once Pass 1 Find who reports to Alice Pass 2 Find who reports to Bob or Carol Last step gave ids 2 and 3. Dana and Eve point at 2, Frank points at 3. Each gets its own boss's depth + 1 and path. Pass 3 Find who reports to the managers Last step gave ids 4, 5 and 6. Five people point at one of them, so five rows join. Pass 4 Nobody reports to ids 7 to 11 The join returns zero rows. An empty step is the stop signal. MySQL returns everything collected. Org chart of the employees table. Highlighted boxes are rows already in org. Click any person to see how their path is built. Lines show manager_id → id. Recursion step ← Back Next → The query, with the part running in this step highlighted How the new rows are found. The recursive part joins employees to the rows the previous pass added. Each match below is one new row for org. Where it starts. The anchor query runs once and picks the row with no manager. That one row is all org holds before the first pass. Alice Chen · manager_id NULL IS NULL kept as the root ui-monospace, SFMono-Regular, Menlo, monospace Start the walk from manager_id NULL no row has id NULL → stop chapters · subqueries and ctes WITH RECURSIVE keeps joining the rows it just found manager_id points at another row in the same table. A recursive CTE starts at one row, then repeats one join: find the people whose boss was found in the last step. When a step finds nobody, it stops. ↻ Start somewhere → join to what you just found → stop when nothing new appears Every recursive query has the same three parts: an anchor, UNION ALL, and a recursive member that reads the CTE's own name.

One column points back at the same table

Alice is the CEO, so her manager_id is NULL. Bob and Carol point at 1. Dana points at 2. Grace points at 4. One SELECT can show Grace's manager_id, but the names above her live on other rows. Following them needs a loop.

The query has three coloured parts

Anchor · runs once UNION ALL · stacks every step Recursive member · repeats Outer query · reads the result org.depth + 1 Each person is one level below the boss row they joined to. CONCAT(org.path, ...) Each person copies the boss's path and adds their own name. CAST(... CHAR(200)) The anchor fixes the column type. Without room, longer paths would not fit.

When the walk never ends

A tree has no loops, but data is made by people. One mistyped manager can make the pointer chain run in a circle, and then every pass finds a row again. Break the data, then try each guard.

Not only trees: make rows out of nothing

A recursive CTE needs no table to walk. Start at 1, add 1 each pass, and stop with a WHERE. Real reports use this to build a calendar so that days with no sales still appear.

Same idea, different spelling

Recursive CTE differences Pass limit MySQL 8+ WITH RECURSIVE cte_max_recursion_depth, 1000 by default No built-in limit. Add your own depth check. SQL Server WITH (no RECURSIVE) 100 by default, change with OPTION (MAXRECURSION n) ! Real-life check Typical uses: an org chart, a category or comment tree, a bill of materials (this part needs these parts), and calendars. Always give the recursive member a way to stop, keep the working columns small, and index the pointer column (here manager_id), because the join runs once per pass.

More courses

  • Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
  • Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
  • React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
  • System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
  • NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
  • Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
  • Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
  • AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
  • Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
  • TypeScript in depth — The type system as a design tool. Inference, narrowing, generics, and the errors that mean the model is wrong — not a catalog of utility types.
  • CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
  • Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
  • Docker — What an image is, why layers cache, and how containers find each other on a network.
  • Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
  • Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
  • AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
  • Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.