advanced

Recursive CTE

7 min readLast updated: 2026-07-23

Overview

A Recursive CTE is a CTE that references itself, allowing you to traverse hierarchical, graph, or tree data structures (such as organizational charts or bill-of-materials).

Learning Objectives

  • Understand the 3 key components of a Recursive CTE: Anchor, Recursive Member, and Termination Condition.
  • Traverse parent-child or tree hierarchies using WITH RECURSIVE.
  • Prevent infinite recursion loops by setting max recursion depth limits.

Detailed Concept Explanation

A Recursive CTE consists of three main parts combined with UNION ALL:

  1. Anchor Member: The initial query that establishes the base result set (e.g., the top-level manager or root node).
  2. Recursive Member: The query that joins the CTE back to the source table to find the next level of child nodes.
  3. Termination Condition: An implicit condition (or explicit depth limit) that stops execution when no new rows are returned.

Code Examples

SQL

sql
-- Traverse an employee-manager hierarchy to find management levels
WITH RECURSIVE EmpHierarchy AS (
    -- 1. Anchor: Find top-level CEO (manager_id IS NULL)
    SELECT emp_id, name, manager_id, 1 AS level
    FROM employees
    WHERE manager_id IS NULL

    UNION ALL

    -- 2. Recursive Member: Join next level employees to previous level managers
    SELECT e.emp_id, e.name, e.manager_id, h.level + 1
    FROM employees e
    JOIN EmpHierarchy h ON e.manager_id = h.emp_id
)
SELECT * FROM EmpHierarchy ORDER BY level, emp_id;

Best Practices

  • Always Use UNION ALL: Use UNION ALL instead of UNION inside recursive CTEs to avoid unnecessary distinct sorting overhead on each iteration step.
  • Set Safety Limits: Guard against circular loops (e.g. A manages B, B manages A) by including a depth limit or using database loop termination hints.

Interview Perspective

Warning

Interview Question: How do you prevent a Recursive CTE from looping infinitely?

You track depth with a counter column (e.g. level + 1) and add a termination check in the WHERE clause (e.g. WHERE level < 100), or use system limits like OPTION (MAXRECURSION 100) in SQL Server.


Interactive Challenges

Challenge 1: Generate Number Sequence

Write a recursive CTE named 'Seq' to generate numbers from 1 to 5.


Summary

Recursive CTEs iterate over parent-child hierarchies using an Anchor, a Recursive Member, and a termination check.