Wicked Smart Data
LearnInsightsAboutContact
Sign InLet's Build
LearnInsightsAboutContact
Sign InLet's Build
Wicked Smart Data

Intelligence, automation, and expert execution — plus an elite library of free knowledge. We turn complexity into competitive advantage.

Start a conversation

Platform

  • Learning Paths
  • Insights
  • RSS Feed

Company

  • About
  • Contact
  • Work With Us

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Wicked Smart Data. All rights reserved.

Intelligence · Automation · Advantage

All Insights
SQL

Optimizing Recursive CTEs for Large Hierarchies: Depth Limits, Cycle Detection, and Execution Plan Analysis

Recursive CTEs break down in predictable ways on large hierarchies: cycles in dirty data, full table scans inside recursive members, and execution plans the optimizer can't accurately estimate. This lesson teaches you exactly how to fix all of it, with real execution plan analysis across PostgreSQL, SQL Server, and BigQuery.

🔥 Expert32 min readNov 30, 2026Updated Nov 30, 2026
Optimizing Recursive CTEs for Large Hierarchies: Depth Limits, Cycle Detection, and Execution Plan Analysis
On this page
  • Introduction
  • Prerequisites
  • How the Recursive Execution Model Actually Works
  • Depth Limits: Safety Mechanism and Business Logic
  • Why Depth Limits Matter
  • Implementing Depth Limits
  • Using Depth in Downstream Logic
  • Database-Specific Depth Controls
  • Cycle Detection: The Data Quality Problem You Can't Ignore
  • Understanding the Cycle Problem
  • Strategy 1: Path-Based Cycle Detection (Most Reliable)
  • Strategy 2: PostgreSQL's Native CYCLE Clause
  • Strategy 3: Self-Reference Detection (Targeted)
  • Pre-Flight Cycle Audit
  • Reading Execution Plans for Recursive Queries
  • PostgreSQL: Recursive Union and Work Tables
  • What to Look For: Diagnostic Checklist
  • SQL Server: The Spool Operator
  • BigQuery: Recursive CTEs and Slot Consumption
  • Indexing Strategies for Recursive Queries
  • The Primary Index: Covering the Recursive Join
  • Filtering in the Anchor: Index-Assisted Entry Points
  • Partial Indexes for Active Hierarchies
  • Materialization Strategies: When to Break the Recursion
  • The Single-Query vs. Multi-Step Tradeoff
  • Incremental Updates to the Closure Table
  • Advanced Optimization Patterns
  • Bidirectional Traversal
  • Pruning the Working Set Early
  • Using LATERAL for Bounded Lookups
  • Hands-On Exercise
  • Common Mistakes & Troubleshooting
  • Mistake 1: Using UNION Instead of UNION ALL in the Recursive Member
  • Mistake 2: Forgetting That Anchors Can Have Multiple Rows
  • Mistake 3: Filtering in the Wrong Place
  • Mistake 4: Carrying Large Columns Through Iterations
  • Mistake 5: Over-relying on Engine Defaults for Cycle Protection
  • Troubleshooting: "Maximum recursion depth exceeded"
  • Summary & Next Steps

Optimizing Recursive CTEs for Large Hierarchies: Depth Limits, Cycle Detection, and Execution Plan Analysis

Introduction

You've built a recursive CTE to traverse your organization's reporting hierarchy. It works beautifully on the test dataset — 50 employees, three levels deep, runs in milliseconds. Then you point it at production: 80,000 employees, acquired subsidiaries layered seven levels deep, a handful of orphaned records pointing back to themselves from a botched data migration. The query spins for 90 seconds before your connection times out. When you finally get it to return results, three of the rows are wrong because a cycle in the data silently duplicated work.

This is the gap between knowing recursive CTEs and mastering them. The basic mechanics — anchor member, recursive member, UNION ALL — are well-covered ground. If you need a refresher on those fundamentals, the lesson on Advanced CTEs: Recursive Queries and Hierarchical Data has you covered. What this lesson tackles is what happens after you understand the basics but before your query is production-ready: the performance failure modes, the data quality traps, and the execution plan signals that tell you exactly what's going wrong and how to fix it.

By the end of this lesson, you'll be equipped to write recursive CTEs that handle genuinely large hierarchies safely and efficiently, detect and handle cycles without crashing, interpret execution plans specific to recursive queries, and choose the right optimization strategy for your database engine and data shape.

What you'll learn:

  • How the recursive CTE execution model works internally and where performance breaks down at scale
  • Multiple cycle detection strategies and when to use each
  • How to implement and tune depth limits as both a safety mechanism and a business logic tool
  • How to read execution plans for recursive queries in PostgreSQL, SQL Server, and BigQuery
  • Indexing strategies, materialization tradeoffs, and query rewrites that meaningfully reduce runtime on large hierarchies

Prerequisites

You should be comfortable writing recursive CTEs, including understanding the anchor/recursive split and how UNION ALL vs UNION affects deduplication. Familiarity with reading basic execution plans (hash joins, index scans, sort operators) will help significantly — the lesson on SQL Query Optimization: Reading Execution Plans — Advanced Performance Analysis is a solid foundation. You should also have access to a database where you can run EXPLAIN ANALYZE or its equivalent.


How the Recursive Execution Model Actually Works

Before optimizing anything, you need a precise mental model of what the database engine is doing. Most documentation describes the algorithm at a high level; let's go deeper.

When the query optimizer encounters a recursive CTE, it sets up what's effectively a work table — an in-memory or on-disk temporary structure depending on your engine and the data volume. The execution proceeds in discrete iterations:

  1. The anchor member runs once and populates the work table with the base result set.
  2. The recursive member runs against the current contents of the work table, producing a new batch of rows.
  3. That new batch replaces the work table's "current" contents (or is appended to a running accumulator, depending on implementation).
  4. Steps 2–3 repeat until the recursive member produces an empty result set.
  5. The final result is the union of all accumulated rows.

The critical word here is "iterations." Each iteration is a full scan of the current working set joined against your base table. If your hierarchy has 10 levels and 10,000 nodes per level, iteration 10 is joining 10,000 rows against a table that might have 100,000 rows. The I/O cost compounds multiplicatively, not additively.

Key insight

Recursive CTEs are not magical tree-walk algorithms. They're iterative hash-join or nested-loop operations. Every performance intuition you have about those join types applies here — including the fact that they're brutally sensitive to working-set size and index availability.

In PostgreSQL, the working table between iterations is called the recursive term result and is re-scanned at each step. SQL Server calls the intermediate structure the spool and materializes it differently depending on whether the optimizer chooses a hash or nested-loop strategy for the self-join. BigQuery's recursive CTE support (added in 2022) uses a different approach: it unrolls iterations at planning time up to its own internal limit, which has implications we'll cover in the execution plan section.

Here's a concrete example to work with throughout this lesson. We'll use an employee hierarchy — a classic but genuinely complex use case when it has 50,000+ rows:

-- Base table: employees with manager relationships
CREATE TABLE employees (
    employee_id    INTEGER PRIMARY KEY,
    full_name      VARCHAR(200) NOT NULL,
    manager_id     INTEGER REFERENCES employees(employee_id),
    department_id  INTEGER,
    is_active      BOOLEAN DEFAULT TRUE,
    hire_date      DATE
);

-- Index that will matter enormously for recursive performance
CREATE INDEX idx_employees_manager_id ON employees(manager_id);

The naive recursive CTE to get the full hierarchy from a given root:

WITH RECURSIVE org_hierarchy AS (
    -- Anchor: start at the CEO (no manager)
    SELECT
        employee_id,
        full_name,
        manager_id,
        0 AS depth,
        ARRAY[employee_id] AS path
    FROM employees
    WHERE manager_id IS NULL

    UNION ALL

    -- Recursive: find each employee's direct reports
    SELECT
        e.employee_id,
        e.full_name,
        e.manager_id,
        h.depth + 1,
        h.path || e.employee_id
    FROM employees e
    INNER JOIN org_hierarchy h ON e.manager_id = h.employee_id
)
SELECT * FROM org_hierarchy ORDER BY depth, full_name;

This works. It will also bring a production database to its knees if the data has problems. Let's talk about those problems systematically.


Depth Limits: Safety Mechanism and Business Logic

Why Depth Limits Matter

A recursive CTE without a depth limit is an infinite loop waiting for a data quality problem to trigger it. Even without true cycles (which we'll handle shortly), consider:

  • An employee whose manager_id points to a terminated employee, who points back to themselves due to a system migration bug
  • A reorganization that temporarily created a valid-looking chain 40 levels deep
  • A test record someone inserted directly into production

The database engine's default recursion limit is your last line of defense. In PostgreSQL, it's max_recursion_depth (default 100 for recursive CTEs in older versions; SQL standard doesn't specify a limit). SQL Server will recurse up to 100 times by default and throw an error. Without your own depth check, you're relying on engine defaults that may or may not match your business reality.

Implementing Depth Limits

The depth counter we included in the CTE above is intentional. Here's how to use it as an actual limit:

WITH RECURSIVE org_hierarchy AS (
    SELECT
        employee_id,
        full_name,
        manager_id,
        0 AS depth,
        ARRAY[employee_id] AS path,
        FALSE AS cycle_detected
    FROM employees
    WHERE manager_id IS NULL

    UNION ALL

    SELECT
        e.employee_id,
        e.full_name,
        e.manager_id,
        h.depth + 1,
        h.path || e.employee_id,
        FALSE AS cycle_detected
    FROM employees e
    INNER JOIN org_hierarchy h ON e.manager_id = h.employee_id
    WHERE h.depth < 15  -- Our business-defined maximum hierarchy depth
      AND NOT h.cycle_detected
)
SELECT * FROM org_hierarchy;

The WHERE h.depth < 15 clause in the recursive member is crucial. It doesn't just prevent runaway execution — it communicates intent. If your organization's hierarchy genuinely shouldn't exceed 15 levels, this is a data quality assertion baked into the query. When someone violates it, you find out through unexpected truncation rather than a timed-out query.

Tip

Set your depth limit to at least 2× the realistic maximum depth in your data. If your org chart runs 7 levels deep normally, set the limit to 15. This gives you a safety buffer for edge cases while still protecting against runaway recursion. Document the limit and the reasoning in a comment — future-you will thank you.

Using Depth in Downstream Logic

Depth isn't just a safety rail. It's often genuinely useful data:

WITH RECURSIVE org_hierarchy AS (
    SELECT
        employee_id,
        full_name,
        manager_id,
        0 AS depth,
        CAST(full_name AS VARCHAR(2000)) AS hierarchy_path,
        ARRAY[employee_id] AS id_path
    FROM employees
    WHERE manager_id IS NULL

    UNION ALL

    SELECT
        e.employee_id,
        e.full_name,
        e.manager_id,
        h.depth + 1,
        h.hierarchy_path || ' > ' || e.full_name,
        h.id_path || e.employee_id
    FROM employees e
    INNER JOIN org_hierarchy h ON e.manager_id = h.employee_id
    WHERE h.depth < 20
)
SELECT
    employee_id,
    full_name,
    depth,
    hierarchy_path,
    -- How many people report up through this person?
    COUNT(*) OVER (PARTITION BY id_path[1]) AS subtree_size
FROM org_hierarchy
ORDER BY id_path;

Here we're combining the recursive CTE with a window function to calculate subtree sizes — something that would require multiple passes without the recursive structure. The id_path array gives us the full lineage for each employee, enabling sophisticated downstream analysis.

Database-Specific Depth Controls

In SQL Server, you can override the default 100-iteration limit using the MAXRECURSION query hint:

WITH org_hierarchy AS (
    -- ... same CTE as above ...
)
SELECT * FROM org_hierarchy
OPTION (MAXRECURSION 50);  -- Fail fast if hierarchy exceeds 50 levels

Setting MAXRECURSION 0 disables the limit entirely — which you should almost never do in production. Setting it lower than the default (say, 25) is a reasonable defensive move when you know your hierarchy depth.

In PostgreSQL, there's no per-query hint equivalent, but you can set it at the session level:

SET max_recursion_depth = 50;
-- Then run your recursive query

BigQuery handles this differently — recursive CTEs are limited to a maximum of 500 iterations and will raise an error if exceeded. There's no way to override this, so depth limits in your query logic are essential.


Cycle Detection: The Data Quality Problem You Can't Ignore

Understanding the Cycle Problem

A cycle in a hierarchy means node A is an ancestor of node B, and node B is also an ancestor of node A. In a manager hierarchy, this would mean employee 42 reports to employee 107, and employee 107 reports (directly or indirectly) to employee 42. This should be impossible by business rules, but in practice it happens through:

  • Direct circular references (A → B → A)
  • Multi-hop cycles (A → B → C → A)
  • Self-references (A → A, where manager_id = employee_id)
  • Data migration errors that bypass referential integrity checks

Without cycle detection, your recursive CTE will loop forever (or until the engine's iteration limit kicks in), potentially returning millions of duplicate rows and exhausting memory.

Strategy 1: Path-Based Cycle Detection (Most Reliable)

The most robust approach tracks the full path of visited nodes and checks whether the next node is already in that path. We've been building toward this with the ARRAY column:

WITH RECURSIVE org_hierarchy AS (
    SELECT
        employee_id,
        full_name,
        manager_id,
        0 AS depth,
        ARRAY[employee_id] AS visited_ids,
        FALSE AS is_cycle
    FROM employees
    WHERE manager_id IS NULL

    UNION ALL

    SELECT
        e.employee_id,
        e.full_name,
        e.manager_id,
        h.depth + 1,
        h.visited_ids || e.employee_id,
        e.employee_id = ANY(h.visited_ids)  -- Cycle check
    FROM employees e
    INNER JOIN org_hierarchy h ON e.manager_id = h.employee_id
    WHERE NOT h.is_cycle  -- Stop recursing once we detect a cycle
      AND h.depth < 25
)
SELECT
    employee_id,
    full_name,
    depth,
    is_cycle,
    visited_ids AS path
FROM org_hierarchy
WHERE is_cycle  -- Inspect which paths have cycles
ORDER BY depth;

This query does something important: instead of silently truncating cycled paths, it surfaces them. You get a result set of every node where a cycle was detected, along with the full path that led there. This is gold for data quality investigation.

Warning

The ARRAY[...] || element approach carries a memory cost proportional to path length × number of nodes. For a 20-level hierarchy with 100,000 nodes, you're accumulating arrays of up to 20 integers for every row in the working set. This is usually fine, but it's something to be aware of when profiling memory pressure on very large hierarchies.

Strategy 2: PostgreSQL's Native CYCLE Clause

PostgreSQL 14 introduced first-class CYCLE syntax, which the standard SQL:1999 specification defined but most engines took decades to implement:

WITH RECURSIVE org_hierarchy AS (
    SELECT
        employee_id,
        full_name,
        manager_id,
        0 AS depth
    FROM employees
    WHERE manager_id IS NULL

    UNION ALL

    SELECT
        e.employee_id,
        e.full_name,
        e.manager_id,
        h.depth + 1
    FROM employees e
    INNER JOIN org_hierarchy h ON e.manager_id = h.employee_id
    WHERE h.depth < 25
)
CYCLE employee_id SET is_cycle USING cycle_path
SELECT * FROM org_hierarchy WHERE NOT is_cycle;

The CYCLE employee_id SET is_cycle USING cycle_path clause tells PostgreSQL to:

  1. Track the employee_id values seen along each path
  2. Set is_cycle = TRUE when it encounters a repeated value
  3. Store the traversal path in cycle_path

This is cleaner than manual array tracking and can be more efficient because the engine has explicit knowledge of what you're doing and can optimize accordingly. The USING cycle_path column is an array of records (or just the key values, depending on configuration) showing the traversal.

Note

SQL Server doesn't support the CYCLE clause as of SQL Server 2022. You'll need manual array tracking there, or the alternative approach of using a separate visited-nodes table with LEFT JOIN / NOT EXISTS checks (though the latter performs poorly at scale — more on this in the anti-patterns section).

Strategy 3: Self-Reference Detection (Targeted)

If your primary concern is self-referencing rows (where manager_id = employee_id), handle these before they ever enter the CTE:

-- Find and report self-references
SELECT employee_id, full_name
FROM employees
WHERE manager_id = employee_id;

-- Then use a filtered CTE that excludes broken records
WITH RECURSIVE org_hierarchy AS (
    SELECT
        employee_id,
        full_name,
        manager_id,
        0 AS depth,
        ARRAY[employee_id] AS visited_ids
    FROM employees
    WHERE manager_id IS NULL
      AND employee_id != COALESCE(manager_id, -1)  -- Exclude self-references

    UNION ALL

    SELECT
        e.employee_id,
        e.full_name,
        e.manager_id,
        h.depth + 1,
        h.visited_ids || e.employee_id
    FROM employees e
    INNER JOIN org_hierarchy h ON e.manager_id = h.employee_id
    WHERE h.depth < 25
      AND e.employee_id != e.manager_id  -- Belt and suspenders
      AND NOT (e.employee_id = ANY(h.visited_ids))
)
SELECT * FROM org_hierarchy;

Handling self-references separately is worth doing even when you have full cycle detection, because self-references are often symptomatic of data issues you want to track and report. See how NULL handling matters here — the COALESCE(manager_id, -1) ensures the check doesn't silently fail when manager_id is NULL.

Pre-Flight Cycle Audit

For production systems, consider running a cycle audit as a separate query before executing the main hierarchy traversal, especially if the hierarchy changes frequently:

-- Detect all cycles using a path-tracking CTE
WITH RECURSIVE cycle_check AS (
    SELECT
        employee_id AS start_node,
        employee_id AS current_node,
        manager_id AS next_node,
        ARRAY[employee_id] AS visited,
        1 AS hop_count
    FROM employees
    WHERE manager_id IS NOT NULL
      AND manager_id != employee_id

    UNION ALL

    SELECT
        cc.start_node,
        e.employee_id,
        e.manager_id,
        cc.visited || e.employee_id,
        cc.hop_count + 1
    FROM employees e
    INNER JOIN cycle_check cc ON e.employee_id = cc.next_node
    WHERE e.employee_id != ANY(cc.visited)
      AND cc.hop_count < 30
)
SELECT DISTINCT start_node, visited AS cycle_path
FROM cycle_check
WHERE next_node = ANY(visited)
ORDER BY start_node;

This is expensive — it effectively traverses the entire graph — so run it in a maintenance window or as a scheduled data quality check, not on every query execution.


Reading Execution Plans for Recursive Queries

Execution plans for recursive CTEs have a specific structure that differs from regular queries, and knowing how to read them is what separates educated optimization from guesswork.

PostgreSQL: Recursive Union and Work Tables

Run EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT) on your recursive query. You'll see an operator called Recursive Union that looks something like:

CTE Scan on org_hierarchy  (cost=0.00..X rows=Y width=Z)
  ->  Recursive Union  (cost=...)
        ->  Seq Scan on employees (anchor)
              Filter: (manager_id IS NULL)
        ->  Hash Join  (cost=...)
              Hash Cond: (e.manager_id = org_hierarchy.employee_id)
              ->  Seq Scan on employees e
              ->  Hash  (cost=...)
                    ->  WorkTable Scan on org_hierarchy

The WorkTable Scan is the key operator. Each iteration, PostgreSQL scans the work table produced by the previous iteration. The join type between the work table and your base table matters enormously:

  • Hash Join on WorkTable: PostgreSQL is rebuilding the hash table every iteration. Each iteration's cost grows proportionally to the size of the previous iteration's result. Watch the actual vs. estimated rows on the Hash Join — if estimates are wildly off, the optimizer may have chosen the wrong join strategy.

  • Nested Loop on WorkTable: This appears when the optimizer believes the work table will be small. For wide, shallow hierarchies (many nodes at each level), this will perform poorly because the work table grows large but the optimizer may not know that in advance.

Key insight

PostgreSQL's row count estimates for recursive CTEs are notoriously unreliable. The optimizer can't know in advance how many iterations will occur or how many rows each iteration will produce. It makes static estimates based on the anchor member's output and applies a fixed multiplier for recursive steps. This is why you'll frequently see massive discrepancies between rows=10 (estimated) and actual rows=48000 in the recursive operator.

For detailed analysis of these plan operators, the guide on Query Profiling and Statistics in SQL covers buffer metrics and row estimation techniques that apply directly to recursive plan analysis.

What to Look For: Diagnostic Checklist

1. Sequential scan on the base table in the recursive member:

->  Seq Scan on employees e  (cost=0.00..2847.00 rows=89000)
      Filter: (manager_id = org_hierarchy.employee_id)

This is the most common performance killer. Every iteration is doing a full table scan of employees to find children of the current nodes. With 89,000 employees, that's 89,000 rows scanned per iteration. If you have 15 levels, that's 15 full scans — 1.3 million row evaluations — just for the join lookups.

Fix: Ensure idx_employees_manager_id exists and is being used:

CREATE INDEX idx_employees_manager_id ON employees(manager_id);

After creating this index, the plan should change to:

->  Index Scan using idx_employees_manager_id on employees e
      Index Cond: (manager_id = org_hierarchy.employee_id)

This changes O(n) per iteration to O(log n) lookup per row in the work table — a dramatic improvement.

2. Excessive work table size:

If BUFFERS output shows temp read=XXXX in the recursive section, the work table has spilled to disk. This happens when the intermediate result set exceeds work_mem. The fix is either increasing work_mem for the session or reducing the result set size through earlier filtering.

3. Array operations in cycle detection slowing things down:

When you're carrying an array of visited IDs through each row, the = ANY(array) check runs for every row in every iteration. For a 100,000-node hierarchy with cycle checking, this can add measurable overhead. Profile specifically by running the same query with and without cycle detection on a known cycle-free dataset.

SQL Server: The Spool Operator

SQL Server's execution plans for recursive CTEs show a Table Spool (Lazy Spool) or Index Spool operator. The spool is SQL Server's equivalent of PostgreSQL's work table, but with different performance characteristics.

Look for these in the plan XML or graphical plan:

Recursive CTE
├── Anchor: Clustered Index Scan on [dbo].[employees]
└── Recursive Member:
    └── Nested Loops (Inner Join)
        ├── Lazy Table Spool (recursive result)
        └── Index Seek on [dbo].[employees] 
              Seek Key: manager_id = Spool.employee_id

The good news: SQL Server will use a seek on the manager_id index automatically if the index exists. The bad news: if the optimizer underestimates spool size, it may allocate an inadequate memory grant, forcing spill to tempdb. Check the SpillLevel attribute in the execution plan XML or watch for the yellow warning triangle in SSMS's graphical plan.

For SQL Server, adding OPTION (MAXRECURSION 50) can sometimes actually improve performance on pathological data because it short-circuits early rather than consuming memory building a massive spool.

BigQuery: Recursive CTEs and Slot Consumption

BigQuery's approach to recursive CTEs differs architecturally. Because BigQuery is a massively parallel columnar engine without traditional row-at-a-time processing, recursive CTEs are handled through an internal unrolling mechanism with bounded iterations.

Use EXPLAIN in BigQuery to see the query plan, but be aware that the recursive steps will appear as separate stages. The key metrics to watch are slot time consumed (not wall-clock time) and bytes shuffled. Large hierarchies in BigQuery often cause excessive shuffling because the join between the working set and the base table requires redistributing data across slots.

Optimization strategies specific to BigQuery:

  • Filter the base table aggressively in the anchor member to minimize the starting set
  • Consider whether a denormalized nested/repeated structure (BigQuery arrays) might serve your use case better than recursion
  • Use LIMIT in your final SELECT to avoid materializing the full result when you only need a subset

Indexing Strategies for Recursive Queries

The index on manager_id we've been discussing is necessary but not always sufficient. Let's think through the full indexing picture.

The Primary Index: Covering the Recursive Join

The join in your recursive member is always child.manager_id = parent.employee_id. The optimal index for the left side of this join (the base table lookup) is on manager_id, ideally a covering index that includes the columns you're selecting:

-- Basic: enables index seek on the join condition
CREATE INDEX idx_employees_manager_id 
ON employees(manager_id);

-- Better: covers the most commonly selected columns
CREATE INDEX idx_employees_manager_covering
ON employees(manager_id) 
INCLUDE (employee_id, full_name, department_id, is_active);

The INCLUDE columns in SQL Server (or additional columns in a PostgreSQL index) mean the engine never has to touch the heap for these reads — it gets everything it needs from the index pages. For a recursive CTE running 15 iterations on 80,000 rows, eliminating 15 × N heap lookups is significant.

Filtering in the Anchor: Index-Assisted Entry Points

If you're not always starting from the root (NULL manager), consider how you're filtering the anchor member. A query that starts at a specific subtree:

WITH RECURSIVE department_hierarchy AS (
    SELECT employee_id, full_name, manager_id, 0 AS depth
    FROM employees
    WHERE employee_id = 4471  -- VP of Engineering, specific subtree

    UNION ALL

    SELECT e.employee_id, e.full_name, e.manager_id, h.depth + 1
    FROM employees e
    INNER JOIN department_hierarchy h ON e.manager_id = h.employee_id
    WHERE h.depth < 10
)
SELECT * FROM department_hierarchy;

This benefits from the primary key index on employee_id for the anchor and the manager_id index for the recursive member. Both are point lookups — this query will perform much better than traversing the full tree and then filtering.

Tip

When possible, design your recursive CTE anchor to use selective filters backed by indexes. Starting from "all employees in department 42" is cheaper than starting from all roots and filtering afterward — even though the final result set is the same size. The earlier you narrow the working set, the fewer iterations the recursive member has to process.

Partial Indexes for Active Hierarchies

If your hierarchy table has an is_active flag and your queries always filter to active records, a partial index can significantly reduce index size and improve cache hit rates:

CREATE INDEX idx_employees_manager_active
ON employees(manager_id)
INCLUDE (employee_id, full_name)
WHERE is_active = TRUE;

This index is only maintained for active employees, so it's smaller and fits more readily in the buffer pool. On a table where 30% of employees are inactive, this could reduce index size by 30% — meaningful when the index is being scanned 15 times per query execution.


Materialization Strategies: When to Break the Recursion

The Single-Query vs. Multi-Step Tradeoff

For large hierarchies that are queried frequently, running the full recursive traversal on every query is often the wrong architectural choice. Consider materializing the hierarchy:

-- Materialized hierarchy table
CREATE TABLE employee_hierarchy_flat (
    ancestor_id    INTEGER NOT NULL,
    descendant_id  INTEGER NOT NULL,
    depth          INTEGER NOT NULL,
    path           INTEGER[] NOT NULL,
    computed_at    TIMESTAMP DEFAULT NOW(),
    PRIMARY KEY (ancestor_id, descendant_id)
);

-- Populate it using the recursive CTE (run periodically)
INSERT INTO employee_hierarchy_flat (ancestor_id, descendant_id, depth, path)
WITH RECURSIVE org_hierarchy AS (
    SELECT
        employee_id AS ancestor_id,
        employee_id AS descendant_id,
        0 AS depth,
        ARRAY[employee_id] AS path
    FROM employees
    WHERE manager_id IS NULL

    UNION ALL

    SELECT
        h.ancestor_id,
        e.employee_id,
        h.depth + 1,
        h.path || e.employee_id
    FROM employees e
    INNER JOIN org_hierarchy h ON e.manager_id = h.descendant_id
    WHERE h.depth < 25
      AND NOT (e.employee_id = ANY(h.path))
)
SELECT ancestor_id, descendant_id, depth, path
FROM org_hierarchy
ON CONFLICT (ancestor_id, descendant_id) 
DO UPDATE SET depth = EXCLUDED.depth, path = EXCLUDED.path, computed_at = NOW();

This is essentially implementing the closure table design pattern — a structure that pre-computes every ancestor/descendant relationship. After materialization, hierarchy queries become simple joins:

-- "Who reports to VP of Engineering, at any level?"
SELECT e.*
FROM employees e
INNER JOIN employee_hierarchy_flat h 
    ON e.employee_id = h.descendant_id
WHERE h.ancestor_id = 4471
ORDER BY h.depth, e.full_name;

-- "What's the full chain of command for employee 8832?"
SELECT e.full_name, h.depth
FROM employees e
INNER JOIN employee_hierarchy_flat h 
    ON e.employee_id = h.ancestor_id
WHERE h.descendant_id = 8832
ORDER BY h.depth DESC;

Both queries are now simple index seeks — no recursion at query time at all. The tradeoff is write complexity: every time the hierarchy changes, you need to update the closure table, either through triggers, application logic, or scheduled refresh. The lesson on Query Optimization with Materialized Views covers refresh strategies that apply directly to this pattern.

Note

The closure table is often the right answer for hierarchies that are read far more often than they change — which describes most organizational or categorical hierarchies. For hierarchies that change constantly (like a live graph database use case), the recursive CTE on demand may be more appropriate despite its performance cost.

Incremental Updates to the Closure Table

A full rebuild of the closure table on every hierarchy change is expensive for large datasets. If you're using PostgreSQL, you can implement incremental updates using a trigger-based approach:

-- After INSERT of a new employee
CREATE OR REPLACE FUNCTION maintain_hierarchy_closure()
RETURNS TRIGGER AS $$
BEGIN
    IF TG_OP = 'INSERT' THEN
        -- Insert self-reference
        INSERT INTO employee_hierarchy_flat (ancestor_id, descendant_id, depth, path)
        VALUES (NEW.employee_id, NEW.employee_id, 0, ARRAY[NEW.employee_id]);

        -- Insert relationships to all ancestors of the new manager
        IF NEW.manager_id IS NOT NULL THEN
            INSERT INTO employee_hierarchy_flat (ancestor_id, descendant_id, depth, path)
            SELECT
                h.ancestor_id,
                NEW.employee_id,
                h.depth + 1,
                h.path || NEW.employee_id
            FROM employee_hierarchy_flat h
            WHERE h.descendant_id = NEW.manager_id;
        END IF;
    END IF;
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

This is significantly more complex than it appears — handling moves (changing manager_id), deletions, and subtree relocations requires careful thought about which closure table rows to delete and re-insert. The Stored Procedures and User-Defined Functions lesson covers the procedural SQL patterns you'll need for robust trigger implementations.


Advanced Optimization Patterns

Bidirectional Traversal

Sometimes you need to traverse both up (find ancestors) and down (find descendants) in the same query. The naive approach is two separate recursive CTEs. The optimized approach uses a single CTE with a direction flag:

WITH RECURSIVE hierarchy_both_ways AS (
    -- Anchor: start node
    SELECT
        employee_id,
        full_name,
        manager_id,
        0 AS depth,
        'root'::text AS direction,
        ARRAY[employee_id] AS path
    FROM employees
    WHERE employee_id = 8832  -- Our target employee

    UNION ALL

    -- Traverse UP: find ancestors
    SELECT
        e.employee_id,
        e.full_name,
        e.manager_id,
        h.depth - 1,
        'ancestor'::text,
        ARRAY[e.employee_id] || h.path
    FROM employees e
    INNER JOIN hierarchy_both_ways h ON e.employee_id = h.manager_id
    WHERE h.direction IN ('root', 'ancestor')
      AND h.depth > -20  -- Limit upward traversal

    UNION ALL

    -- Traverse DOWN: find descendants
    SELECT
        e.employee_id,
        e.full_name,
        e.manager_id,
        h.depth + 1,
        'descendant'::text,
        h.path || e.employee_id
    FROM employees e
    INNER JOIN hierarchy_both_ways h ON e.manager_id = h.employee_id
    WHERE h.direction IN ('root', 'descendant')
      AND h.depth < 20   -- Limit downward traversal
      AND NOT (e.employee_id = ANY(h.path))
)
SELECT employee_id, full_name, depth, direction, path
FROM hierarchy_both_ways
ORDER BY depth;

Warning

Bidirectional traversal significantly increases working set size because you're growing the result in two directions simultaneously. The cycle detection (using NOT (e.employee_id = ANY(h.path))) is especially important here because the downward traversal could otherwise encounter ancestors that are also the target's descendants if data is corrupted. Profile this carefully on large datasets.

Pruning the Working Set Early

One of the most effective optimizations for recursive queries is reducing the working set as early as possible. If you're only interested in active employees in certain departments, filter them in the anchor:

-- Less efficient: filter at the end
WITH RECURSIVE org_hierarchy AS ( ... all employees ... )
SELECT * FROM org_hierarchy WHERE department_id = 15 AND is_active = TRUE;

-- More efficient: filter in the anchor and propagate
WITH RECURSIVE org_hierarchy AS (
    SELECT employee_id, full_name, manager_id, department_id, 0 AS depth
    FROM employees
    WHERE manager_id IS NULL
      AND is_active = TRUE  -- Only active roots

    UNION ALL

    SELECT e.employee_id, e.full_name, e.manager_id, e.department_id, h.depth + 1
    FROM employees e
    INNER JOIN org_hierarchy h ON e.manager_id = h.employee_id
    WHERE e.is_active = TRUE  -- Only recurse through active employees
      AND h.depth < 20
)
SELECT * FROM org_hierarchy WHERE department_id = 15;

The second version processes fewer rows in every iteration because inactive employees are excluded from the recursive member. The final WHERE department_id = 15 still runs at the end, but on a much smaller result set.

Using LATERAL for Bounded Lookups

For use cases where you only need immediate children (depth = 1) or a fixed number of levels, LATERAL joins can be more efficient than recursion:

-- Get 3 levels of hierarchy without recursion
SELECT
    l1.employee_id AS level1_id,
    l1.full_name AS level1_name,
    l2.employee_id AS level2_id,
    l2.full_name AS level2_name,
    l3.employee_id AS level3_id,
    l3.full_name AS level3_name
FROM employees l1
LEFT JOIN LATERAL (
    SELECT employee_id, full_name
    FROM employees
    WHERE manager_id = l1.employee_id
) l2 ON TRUE
LEFT JOIN LATERAL (
    SELECT employee_id, full_name
    FROM employees
    WHERE manager_id = l2.employee_id
) l3 ON TRUE
WHERE l1.manager_id IS NULL;  -- Start at roots

This is only practical for a fixed, known number of levels, but for depth-limited UIs (like a 3-level org chart display), it can outperform a recursive CTE because the optimizer can reason about each join independently.


Hands-On Exercise

Work through this scenario to consolidate everything from this lesson. You'll need a database with recursive CTE support (PostgreSQL 10+, SQL Server 2008+, or BigQuery).

Setup:

-- Create a category tree (e-commerce product taxonomy)
CREATE TABLE product_categories (
    category_id    INTEGER PRIMARY KEY,
    category_name  VARCHAR(200) NOT NULL,
    parent_id      INTEGER REFERENCES product_categories(category_id),
    is_active      BOOLEAN DEFAULT TRUE,
    display_order  INTEGER DEFAULT 0
);

-- Insert sample data with an intentional data quality issue
INSERT INTO product_categories VALUES
(1, 'All Products', NULL, TRUE, 0),
(2, 'Electronics', 1, TRUE, 1),
(3, 'Computers', 2, TRUE, 1),
(4, 'Laptops', 3, TRUE, 1),
(5, 'Gaming Laptops', 4, TRUE, 1),
(6, 'Business Laptops', 4, TRUE, 2),
(7, 'Phones', 2, TRUE, 2),
(8, 'Smartphones', 7, TRUE, 1),
(9, 'Clothing', 1, TRUE, 2),
(10, 'Mens', 9, TRUE, 1),
(11, 'Womens', 9, TRUE, 2),
(12, 'Orphaned Category', 15, TRUE, 0),  -- References non-existent parent
(13, 'Cycle Node A', 1, TRUE, 0),
(14, 'Cycle Node B', 13, TRUE, 0);

-- Create the cycle: B's child points back to A
UPDATE product_categories SET parent_id = 14 WHERE category_id = 13;

CREATE INDEX idx_categories_parent ON product_categories(parent_id);

Exercise Tasks:

Task 1: Write a recursive CTE that traverses the full category hierarchy from the root, with depth limiting set to a reasonable maximum for a product taxonomy. Include a breadcrumb column showing the full path (e.g., "All Products > Electronics > Computers").

Task 2: Add cycle detection to your query from Task 1. The query should return all categories, marking which ones are part of a cycle rather than silently dropping them or infinitely looping.

Task 3: Run EXPLAIN ANALYZE on your query and identify: (a) whether the manager_id index is being used, (b) the estimated vs. actual row counts for the recursive member, and (c) whether any operators show high actual time vs. estimated cost.

Task 4: Rewrite the query to handle the orphaned category (ID 12, which references a non-existent parent_id of 15) gracefully. The query should still return all valid categories and separately report orphaned ones.

Task 5: Write a query using your recursive CTE that counts the total number of products that would appear in each category when you include all subcategories. (You can mock this by assuming category_id * 10 products exist in each leaf category.)

Expected insight: For Task 3, you should see that the anchor member uses a sequential scan (expected — it's filtering on NULL parent_id) while the recursive member uses the index on parent_id. If the recursive member is also showing sequential scans, your index isn't being picked up and you should investigate whether statistics are current.


Common Mistakes & Troubleshooting

Mistake 1: Using UNION Instead of UNION ALL in the Recursive Member

-- This will remove duplicate rows between iterations, not detect cycles
WITH RECURSIVE ... AS (
    ... anchor ...
    UNION  -- Wrong! Use UNION ALL
    ... recursive member ...
)

UNION in the recursive member attempts deduplication between iterations, which is both expensive and semantically wrong for most hierarchy traversals. The correct tool for cycle prevention is explicit path tracking, not UNION. If you need deduplication of the final result, apply it in the outer query.

Mistake 2: Forgetting That Anchors Can Have Multiple Rows

Your anchor member doesn't have to return one row. If you have multiple root nodes (e.g., a forest rather than a single tree), your anchor naturally returns multiple rows:

-- Correct: anchor returns all roots
WHERE parent_id IS NULL  -- Could be hundreds of root categories

Thinking of the anchor as "the starting node" rather than "the starting set" leads to unnecessary wrapper queries and missed optimizations.

Mistake 3: Filtering in the Wrong Place

-- Slow: filter happens on the full result after all recursion completes
WITH RECURSIVE hier AS (...)
SELECT * FROM hier WHERE depth = 3;  -- Processes all 50,000 nodes first

-- Fast: use depth in the recursive member to stop early
WITH RECURSIVE hier AS (
    ... anchor (depth = 0) ...
    UNION ALL
    ... recursive WHERE h.depth < 3 ...  -- Stop after 3 levels
)
SELECT * FROM hier WHERE depth = 3;

The filter in the outer SELECT doesn't push down into the recursion. If you only need nodes at a certain depth, limit traversal in the recursive member's WHERE clause.

Mistake 4: Carrying Large Columns Through Iterations

-- Expensive: carrying large text columns through every iteration
WITH RECURSIVE hier AS (
    SELECT
        employee_id,
        full_name,
        bio_text,  -- Could be thousands of characters per row
        notes,
        ARRAY[employee_id] AS path,
        h.depth
    ...
)

Every row in every iteration carries all selected columns. For large text columns, this multiplies memory usage dramatically. Select only what you need in the CTE, and join back to the original table in the final query:

-- Better: carry only keys through the recursion, join at the end
WITH RECURSIVE hier AS (
    SELECT employee_id, manager_id, 0 AS depth, ARRAY[employee_id] AS path
    FROM employees WHERE manager_id IS NULL
    UNION ALL
    SELECT e.employee_id, e.manager_id, h.depth + 1, h.path || e.employee_id
    FROM employees e JOIN hier h ON e.manager_id = h.employee_id
    WHERE h.depth < 25 AND NOT (e.employee_id = ANY(h.path))
)
SELECT h.employee_id, h.depth, e.full_name, e.bio_text, e.notes
FROM hier h
JOIN employees e ON h.employee_id = e.employee_id;

Mistake 5: Over-relying on Engine Defaults for Cycle Protection

The 100-iteration default in SQL Server or the error at 500 iterations in BigQuery is not cycle detection — it's a runaway query killer. It won't tell you which data caused the problem, it won't surface the cycle path, and it will make your query fail rather than gracefully handle bad data. Always implement explicit cycle detection in production queries.

Troubleshooting: "Maximum recursion depth exceeded"

If you hit this error, work through this checklist:

  1. Is your depth limit realistic for your data? Add a MAX(depth) aggregation to understand your actual data depth.
  2. Is there a cycle? Run the cycle audit query from earlier in this lesson.
  3. Are your base conditions correct? An anchor that never correctly identifies true root nodes will cause the recursive member to recurse upward indefinitely.
  4. Is the recursive join inverted? ON e.manager_id = h.employee_id (find children) vs ON e.employee_id = h.manager_id (find parents) — getting these backwards causes infinite loops.

Summary & Next Steps

Recursive CTEs for large hierarchies fail in predictable ways: they hit cycles in dirty data, they run full table scans inside their recursive members, they carry unnecessary columns through dozens of iterations, and they produce plans the optimizer can't accurately estimate. Each of these failures has a concrete fix.

The core toolkit you've built in this lesson:

  • Depth limits as both safety mechanisms and business logic assertions — always explicit, never relying on engine defaults
  • Path-based cycle detection using arrays of visited node IDs, with PostgreSQL's native CYCLE clause as the cleaner option when available
  • Index-aware query design — the manager_id / parent_id covering index is non-negotiable for recursive queries on large tables
  • Execution plan reading — knowing how to interpret WorkTable Scan, the spool operator, and row count estimation failures specific to recursive CTEs
  • Materialization via closure tables for read-heavy hierarchies where write complexity is acceptable
  • Working-set minimization through early filtering in anchor and recursive members

The natural next topics to pursue from here: for graphs with non-tree relationships (many-to-many edges rather than strict parent-child), the lesson on Graph Traversal in SQL: Recursive CTEs and Adjacency Lists for Network and Relationship Analysis extends these techniques to genuine graph problems. For the broader performance tuning context — particularly indexing strategy for the tables your recursive CTEs are hitting — the deep-dive on Database Performance Tuning: Advanced Indexing Strategies and Query Rewriting for Production Systems covers the full optimization toolkit. And if you're building stored procedures or triggers to maintain closure tables, Stored Procedures and User-Defined Functions: Building Reusable SQL Logic has the procedural SQL patterns you'll need.

Hierarchical data is everywhere — org charts, product taxonomies, geographic regions, bill of materials, comment threads. The engineers who can query it correctly and efficiently at scale are genuinely rare, and the gap between a naive recursive CTE and a production-ready one is exactly the kind of expertise this lesson was built to give you.

Work With Us

From insight to implementation

Reading is the start. When you're ready to build the data, automation, or AI systems behind it, our team turns strategy into shipped results.

Let's Build

Advanced SQL Queries

Previous

Writing SQL to Compare Rows Within a Partition Using LEAD and LAG: Calculating Deltas, Detecting Changes, and Handling Boundary Conditions

Related Insights

SQLFoundation

Writing SQL to Calculate Totals, Averages, and Counts Across Filtered Subsets: Combining WHERE, GROUP BY, and Aggregate Functions in One Query

15 min
SQLPractitioner

Writing SQL to Compare Rows Within a Partition Using LEAD and LAG: Calculating Deltas, Detecting Changes, and Handling Boundary Conditions

20 min
SQLExpert

Writing SQL to Identify and Exclude Outliers Using Subqueries and Aggregate Thresholds

28 min

On this page

  • Introduction
  • Prerequisites
  • How the Recursive Execution Model Actually Works
  • Depth Limits: Safety Mechanism and Business Logic
  • Why Depth Limits Matter
  • Implementing Depth Limits
  • Using Depth in Downstream Logic
  • Database-Specific Depth Controls
  • Cycle Detection: The Data Quality Problem You Can't Ignore
  • Understanding the Cycle Problem
  • Strategy 1: Path-Based Cycle Detection (Most Reliable)
  • Strategy 2: PostgreSQL's Native CYCLE Clause
  • Strategy 3: Self-Reference Detection (Targeted)
  • Pre-Flight Cycle Audit
  • Reading Execution Plans for Recursive Queries
  • PostgreSQL: Recursive Union and Work Tables
  • What to Look For: Diagnostic Checklist
  • SQL Server: The Spool Operator
  • BigQuery: Recursive CTEs and Slot Consumption
  • Indexing Strategies for Recursive Queries
  • The Primary Index: Covering the Recursive Join
  • Filtering in the Anchor: Index-Assisted Entry Points
  • Partial Indexes for Active Hierarchies
  • Materialization Strategies: When to Break the Recursion
  • The Single-Query vs. Multi-Step Tradeoff
  • Incremental Updates to the Closure Table
  • Advanced Optimization Patterns
  • Bidirectional Traversal
  • Pruning the Working Set Early
  • Using LATERAL for Bounded Lookups
  • Hands-On Exercise
  • Common Mistakes & Troubleshooting
  • Mistake 1: Using UNION Instead of UNION ALL in the Recursive Member
  • Mistake 2: Forgetting That Anchors Can Have Multiple Rows
  • Mistake 3: Filtering in the Wrong Place
  • Mistake 4: Carrying Large Columns Through Iterations
  • Mistake 5: Over-relying on Engine Defaults for Cycle Protection
  • Troubleshooting: "Maximum recursion depth exceeded"
  • Summary & Next Steps