Browse SQL Topics ▼

Recursive CTEs (Hierarchies & Trees)

📂 Subqueries & CTEs 📘 Lesson 55 of 81

Traverse tree structures, bill-of-materials, and organizational charts recursively using WITH RECURSIVE.

Recursive CTEs (Hierarchies & Trees) is an essential topic in SQL and relational database engineering.

Overview

Building on foundational principles introduced in common-table-expressions, mastering recursive ctes (hierarchies & trees) provides the core mental model and practical query skills needed for production relational database engineering.

WITH RECURSIVE org_chart AS (
    -- Anchor member: CEO
    SELECT id, name, manager_id, 1 AS level
    FROM employees WHERE manager_id IS NULL
    UNION ALL
    -- Recursive member: Subordinates
    SELECT e.id, e.name, e.manager_id, o.level + 1
    FROM employees e
    JOIN org_chart o ON o.id = e.manager_id
)
SELECT * FROM org_chart ORDER BY level, name;

Key Concepts

  • Understand the fundamental syntax, conventions, and mental model.
  • Avoid common beginner traps, data type mismatches, and performance pitfalls.
  • Apply practical idioms directly in production applications.

[!TIP] Master this concept to build a rock-solid foundation. Next, proceed to window-functions-over.

Test your understanding of Recursive CTEs (Hierarchies & Trees)

Quick interactive practice questions with instant feedback.

Take Quiz →