🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Recursive CTEs

Common Table ExpressionsRecursive CTE🟢 Free Lesson
Common Table Expressions

Recursive CTEs

Traverse hierarchies, graphs, and tree structures with self-referencing queries.

  • Base Case — Starting point of the recursion (anchor member)
  • Recursive Case — Self-referencing query that joins back to itself
  • Termination — Stops when no more rows are produced Recursive CTEs solve problems that iterative code handles — entirely in SQL.

What Is a Recursive CTE?

Recursive CTE: Tree TraversalCEO (Level 1)VP EngineeringVP SalesEng ManagerTech LeadSales MgrAccount ExecAnchor: CEO (no manager)Recursive: JOIN on manager_idStop: no more reports found

Recursive CTEs are essential for traversing hierarchical data like organizational charts, bill of materials, file systems, category trees, and network graphs.

Structure

ComponentPurposeExample
Anchor MemberStarting rows (non-recursive)Top-level managers
UNION ALLCombines anchor and recursive resultsAlways required
Recursive MemberJoins back to the CTEFind direct reports
TerminationRecursive member returns empty setNo more children found

Basic Syntax

-- Recursive CTE skeleton
WITH RECURSIVE cte_name AS (
    -- Anchor member: starting point
    SELECT columns
    FROM table
    WHERE condition

    UNION ALL

    -- Recursive member: self-referencing
    SELECT columns
    FROM table
    JOIN cte_name ON join_condition
)
SELECT * FROM cte_name;

Example 1: Organizational Hierarchy

-- Employee hierarchy with levels and path
WITH RECURSIVE org_hierarchy AS (
    -- Anchor: top-level employees (no manager)
    SELECT
        employee_id,
        employee_name,
        manager_id,
        1 AS level,
        employee_name AS hierarchy_path
    FROM employees
    WHERE manager_id IS NULL

    UNION ALL

    -- Recursive: employees with managers
    SELECT
        e.employee_id,
        e.employee_name,
        e.manager_id,
        oh.level + 1,
        CONCAT(oh.hierarchy_path, ' → ', e.employee_name)
    FROM employees e
    JOIN org_hierarchy oh ON e.manager_id = oh.employee_id
)
SELECT
    employee_id,
    employee_name,
    level,
    hierarchy_path
FROM org_hierarchy
ORDER BY level, employee_name;

Output Example

employee_namelevelhierarchy_path
CEO1CEO
VP Engineering2CEO → VP Engineering
VP Sales2CEO → VP Sales
Engineering Manager3CEO → VP Engineering → Engineering Manager
Developer 14CEO → VP Engineering → Engineering Manager → Developer 1

Example 2: Bill of Materials

-- Calculate total cost of a product including all components
WITH RECURSIVE bom AS (
    -- Anchor: top-level product
    SELECT
        product_id,
        component_id,
        quantity,
        unit_cost,
        quantity * unit_cost AS total_cost,
        1 AS depth
    FROM bill_of_materials
    WHERE product_id = 'FINAL_PRODUCT'

    UNION ALL

    -- Recursive: sub-components
    SELECT
        b.product_id,
        bom.component_id,
        b.quantity * bom.quantity,
        bom.unit_cost,
        b.quantity * bom.quantity * bom.unit_cost,
        bom.depth + 1
    FROM bill_of_materials b
    JOIN bom ON b.product_id = bom.component_id
    WHERE bom.depth < 10  -- Safety limit
)
SELECT
    component_id,
    SUM(total_cost) AS component_total_cost
FROM bom
GROUP BY component_id
ORDER BY component_total_cost DESC;

Example 3: Category Tree Traversal

-- Flatten a nested category hierarchy
WITH RECURSIVE category_tree AS (
    -- Anchor: root categories
    SELECT
        category_id,
        category_name,
        parent_id,
        1 AS depth,
        category_name AS full_path
    FROM categories
    WHERE parent_id IS NULL

    UNION ALL

    -- Recursive: child categories
    SELECT
        c.category_id,
        c.category_name,
        c.parent_id,
        ct.depth + 1,
        CONCAT(ct.full_path, ' > ', c.category_name)
    FROM categories c
    JOIN category_tree ct ON c.parent_id = ct.category_id
    WHERE ct.depth < 5
)
SELECT
    category_id,
    category_name,
    depth,
    full_path
FROM category_tree
ORDER BY full_path;

Example 4: Date Series Generation

-- Generate a series of consecutive dates
WITH RECURSIVE date_series AS (
    -- Anchor: start date
    SELECT '2024-01-01' AS series_date

    UNION ALL

    -- Recursive: add one day
    SELECT DATE_ADD(series_date, INTERVAL 1 DAY)
    FROM date_series
    WHERE series_date < '2024-12-31'
)
SELECT series_date
FROM date_series;

Example 5: Graph Traversal

-- Find all reachable nodes from a starting point in a graph
WITH RECURSIVE graph_walk AS (
    -- Anchor: starting node
    SELECT
        node_id,
        node_name,
        0 AS distance,
        CAST(node_name AS CHAR(500)) AS path
    FROM nodes
    WHERE node_id = 1

    UNION ALL

    -- Recursive: follow edges
    SELECT
        n.node_id,
        n.node_name,
        gw.distance + 1,
        CONCAT(gw.path, ' → ', n.node_name)
    FROM nodes n
    JOIN edges e ON n.node_id = e.target_node_id
    JOIN graph_walk gw ON e.source_node_id = gw.node_id
    WHERE gw.distance < 5
      AND NOT FIND_IN_SET(n.node_id, REPLACE(gw.path, ' → ', ','))
)
SELECT node_id, node_name, distance, path
FROM graph_walk
ORDER BY distance, node_name;

Cycle Detection

-- Safe recursive CTE with cycle detection
WITH RECURSIVE traversal AS (
    SELECT
        node_id,
        ARRAY[node_id] AS visited_path,
        0 AS depth
    FROM nodes
    WHERE node_id = 'START'

    UNION ALL

    SELECT
        n.node_id,
        t.visited_path || n.node_id,
        t.depth + 1
    FROM nodes n
    JOIN edges e ON n.node_id = e.target_node_id
    JOIN traversal t ON e.source_node_id = t.node_id
    WHERE t.depth < 10
      AND n.node_id <> ALL(t.visited_path)  -- Cycle detection
)
SELECT node_id, visited_path, depth
FROM traversal
ORDER BY depth;

Best Practices

PracticeReason
Always include depth limitPrevent infinite recursion
Detect cycles in graph dataAvoid infinite loops
Use UNION ALL (not UNION)UNION deduplicates, breaking recursion
Test with small datasets firstRecursive CTEs can be expensive
Add safety limitsDefault recursion limits vary by database

Recursive CTE vs Alternatives

ApproachProsCons
Recursive CTEPure SQL, readableMay hit recursion limits
Iterative code (app layer)Full control, no limitsMore code, network overhead
Nested sets modelFast readsComplex writes
Materialized pathFast ancestry lookupsPath string manipulation

Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Related Tutorials

Content with similar topics across other courses

Need Expert SQL Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement