SQL Topics
Recursive CTE
title: Recursive CTE
In the previous lesson, you learned about:
Common Table Expressions (CTEs)A normal CTE creates a temporary result set and allows you to simplify complex queries.
However, some data structures contain:
Hierarchies
Parent-Child Relationships
Tree Structures
Recursive RelationshipsExamples:
Employee → Manager
Category → Subcategory
Folder → Subfolder
Course → PrerequisiteTo query these structures efficiently, SQL provides:
Recursive CTEA Recursive CTE is a Common Table Expression that references itself during execution.
It repeatedly executes until a stopping condition is met.
What is a Recursive CTE?
A Recursive CTE is a CTE that references itself to repeatedly process hierarchical or recursive data.
Unlike a normal CTE:
Normal CTE
Runs OnceRecursive CTE:
Runs Repeatedly
Until Stop Condition ReachedSimple Definition
A Recursive CTE is a Common Table Expression that calls itself to generate hierarchical or recursive query results.
Why Are Recursive CTEs Needed?
Suppose a company has this structure:
Question:
Show Entire Organization HierarchySimple SELECT statements cannot easily handle this.
Recursive CTEs solve this problem.
How Recursive CTE Works
A Recursive CTE contains:
Anchor Query
+
Recursive QueryAnchor Query
Starting point.
Returns initial rows.
Example:
CEORecursive Query
References the CTE itself.
Finds additional rows.
Example:
Managers
EmployeesExecution Flow
Anchor Query
↓
Result Generated
↓
Recursive Query Executes
↓
More Rows Found
↓
Repeat
↓
Stop Condition MetRecursive CTE Syntax
WITH CTE_Name AS
(
Anchor Query
UNION ALL
Recursive Query
)
SELECT *
FROM CTE_Name;Understanding the Syntax
WITH
Starts the CTE.
Anchor Query
Initial result set.
UNION ALL
Combines results.
Recursive Query
References the CTE itself.
Final SELECT
Displays all generated rows.
Simple Number Generation Example
Generate numbers:
1 To 5Recursive CTE
WITH Numbers AS
(
SELECT 1 AS Num
UNION ALL
SELECT Num + 1
FROM Numbers
WHERE Num < 5
)
SELECT *
FROM Numbers;Output
1
2
3
4
5Step-by-Step Execution
Anchor Query:
SELECT 1Output:
1Recursive Query:
1 + 1Output:
2Again:
2 + 1Output:
3Continues until:
Num < 5becomes false.
Employee Hierarchy Example
Employees Table:
| EmployeeID | EmployeeName | ManagerID |
|---|---|---|
| 1 | CEO | NULL |
| 2 | Rahul | 1 |
| 3 | Priya | 1 |
| 4 | Amit | 2 |
| 5 | Neha | 2 |
Goal
Retrieve complete hierarchy.
Recursive CTE
WITH EmployeeHierarchy AS
(
SELECT
EmployeeID,
EmployeeName,
ManagerID
FROM Employees
WHERE ManagerID IS NULL
UNION ALL
SELECT
E.EmployeeID,
E.EmployeeName,
E.ManagerID
FROM Employees E
JOIN EmployeeHierarchy EH
ON E.ManagerID =
EH.EmployeeID
)
SELECT *
FROM EmployeeHierarchy;Output
CEO
Rahul
Priya
Amit
NehaHierarchy retrieved automatically.
Organization Chart Example
Structure:
Recursive CTE can retrieve entire reporting structure.
Folder Structure Example
Directory:
Recursive CTE traverses all folders.
Product Category Example
Categories:
Recursive query retrieves complete category tree.
University Example
Course Structure:
Programming Basics
↓
Data Structures
↓
Algorithms
↓
Advanced AlgorithmsRecursive CTE retrieves prerequisite chains.
Banking Example
Branch Structure:
Head Office
↓
Regional Office
↓
Branch OfficeRecursive queries display hierarchy.
Understanding UNION ALL
Recursive CTEs almost always use:
UNION ALLbecause:
Faster
Preserves Duplicates
Required For RecursionRecursive Depth
Each execution creates a new level.
Example:
Level 1
CEO
Level 2
Managers
Level 3
Employees
Level 4
InternsAdding Level Information
WITH EmployeeHierarchy AS
(
SELECT
EmployeeID,
EmployeeName,
ManagerID,
1 AS Level
FROM Employees
WHERE ManagerID IS NULL
UNION ALL
SELECT
E.EmployeeID,
E.EmployeeName,
E.ManagerID,
EH.Level + 1
FROM Employees E
JOIN EmployeeHierarchy EH
ON E.ManagerID =
EH.EmployeeID
)
SELECT *
FROM EmployeeHierarchy;Output Example
| Employee | Level |
|---|---|
| CEO | 1 |
| Rahul | 2 |
| Priya | 2 |
| Amit | 3 |
| Neha | 3 |
Stop Condition
Every recursive CTE must have:
Termination ConditionWithout it:
Infinite Loopcan occur.
Wrong Example
WITH Numbers AS
(
SELECT 1
UNION ALL
SELECT Num + 1
FROM Numbers
)No stop condition.
Result:
Infinite RecursionCorrect Example
WHERE Num < 5Stops recursion safely.
Recursive CTE vs Loop
Traditional Programming:
FOR LOOP
WHILE LOOPSQL Equivalent:
Recursive CTERecursive CTE vs Self Join
Self Join:
Limited Levels
Complex QueriesRecursive CTE:
Unlimited Hierarchy Levels
Cleaner QueriesAdvantages of Recursive CTEs
Handles Hierarchical Data
Primary use case.
Cleaner Queries
More readable than multiple joins.
Dynamic Depth
Works with unknown hierarchy levels.
Reusable Logic
Easy to maintain.
Powerful Reporting
Useful for analytics.
Disadvantages of Recursive CTEs
Performance Cost
Large hierarchies may be expensive.
Infinite Loop Risk
Missing stop conditions create problems.
Memory Usage
Large recursion consumes resources.
Complexity
Harder for beginners.
Common Mistakes
Missing Stop Condition
Most common error.
Using UNION Instead of UNION ALL
Can reduce performance.
Deep Recursion
May exceed database recursion limits.
Poor Indexing
Hierarchy queries may become slow.
Best Practices
Always Include Stop Condition
Prevent infinite loops.
Use UNION ALL
Better performance.
Index Parent Columns
Improve recursive joins.
Limit Recursion Depth
Protect server resources.
Test Large Hierarchies
Evaluate performance.
Common Interview Questions
What is a Recursive CTE?
A CTE that references itself.
What are the two parts of a Recursive CTE?
Anchor Query
Recursive QueryWhy is UNION ALL used?
To combine recursive results efficiently.
What is the purpose of the stop condition?
To prevent infinite recursion.
Where are Recursive CTEs commonly used?
Hierarchies, organizational charts, category trees, and folder structures.
Summary
Recursive CTEs are powerful SQL constructs that allow queries to process hierarchical and recursive data structures. They consist of an anchor query and a recursive query that repeatedly executes until a stop condition is reached.
In this lesson, you learned:
- What Recursive CTEs are
- Recursive CTE syntax
- Anchor Query
- Recursive Query
- Employee hierarchy examples
- Folder structure examples
- Product category trees
- Stop conditions
- Advantages and disadvantages
- Best practices
Mastering Recursive CTEs is essential because hierarchical data is common in enterprise applications, reporting systems, organizational structures, and analytics platforms.
Next Step
Continue to the next lesson:
Window Functions →
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Recursive CTE.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this SQL topic.
Search Terms
sql, sql complete guide, sql tutorial, sql notes, complete, guide, advanced, recursive
Related SQL Topics