Recursive CTE

SQL · Extra Concepts

Theory

A recursive CTE is a CTE that refers to itself, letting SQL walk through hierarchies such as org charts, category trees or bill-of-materials. It has two parts joined by UNION ALL. The anchor (base case) selects the starting rows, for example the CEO whose manager_id IS NULL. The recursive part joins the table back to the CTE's previous rows to find the next level, for example employees whose manager_id matches an id already found.

The database runs it in rounds: it runs the anchor, then repeatedly runs the recursive part using only the rows produced in the last round, and stops when a round returns no new rows. A level counter (level + 1) records the depth. PostgreSQL, MySQL, SQLite and Snowflake write WITH RECURSIVE; SQL Server and Oracle write just WITH. If the data contains a cycle (A manages B, B manages A), the recursion never ends, so add a depth limit such as WHERE level < 10, or use the database's cycle-detection options.

Why we use it

Hierarchies can be any depth, so you cannot write a fixed number of self-joins. A recursive CTE follows parent-child links level by level until it reaches the bottom, whatever the depth.

When to use it

Use it for org charts, folder or category trees, route finding and generating number or date series. For a fixed, known depth (just manager and employee) a simple self-join is easier. Always guard against cycles.

How it works

  1. Run the anchor: rows WHERE manager_id IS NULL (level 1)
  2. Run the recursive part: join employees to the last round's rows
  3. Add the new rows with level + 1
  4. Did this round add new rows? Yes: Recurse again on those rows. No: Stop recursing.
  5. Return all rows collected (UNION ALL)

Syntax

WITH RECURSIVE cte_name AS (
  base_case
  UNION ALL
  recursive_case
)
SELECT * FROM cte_name;

Example

WITH RECURSIVE org_chart AS (
  SELECT id, name, manager_id, 1 AS level FROM employees WHERE manager_id IS NULL
  UNION ALL
  SELECT e.id, e.name, e.manager_id, oc.level + 1
  FROM employees e JOIN org_chart oc ON e.manager_id = oc.id
)
SELECT * FROM org_chart;

Key points

SQL topics

Introduction to SQL

Querying Data

Sorting Rows

Limiting Rows

Filtering Rows

Joining Multiple Tables

Grouping Rows

SET Operators

Working with Tables

Modifying Data

Views & Triggers

Conditional Expressions

SQL Subqueries

Aggregate Functions

Window Functions

String Functions

Date Functions

Math Functions

Extra Concepts

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Master SQL from Zero to Pro

All SQL topics in one place. Click any topic in the sidebar — content opens right here without leaving the page.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice SQL Online Solve 150 SQL interview problems in a live editor with instant checking. Start practising →
Section {{ sec.num }}

{{ sec.label }}

SQL  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ rich.why }}

When to use it

{{ rich.when }}

Diagram

{{ rich.dg.caption }}

{{ tb.title }}
{{ c.v }}
{{ rich.dg.op }}
➜
{{ rich.dg.output.title }}
{{ c.v }}
{{ nd.label }}
{{ nd.sub }}
{{ nd.label }}
{{ nd.sub }}
{{ rich.dg.left.title }}
{{ it }}
{{ rich.dg.right.title }}
{{ it }}
Flowchart — how it works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Syntax
{{ current.syntax }}
Example
{{ current.example }}
▶ Try It Live — runs against a real sample database
{{ liveError }}
{{ col }}
{{ cell }}
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic