SQL Notes
Learn Recursive Common Table Expressions (Recursive CTEs) in SQL in detail, understand recursion, hierarchical queries, organizational charts, tree structures, and real-world examples.
In the previous lesson, you learned about:
Common Table Expressions (CTEs)A normal CTE creates a temporary result set and lets you clean up complex queries.
But here's the thing—some data is *hierarchical*. You've got:
Hierarchies
Parent-Child Relationships
Tree Structures
Recursive RelationshipsReal-world examples:
Employee → Manager
Category → Subcategory
Folder → Subfolder
Course → PrerequisiteWhen you need to query these, SQL gives you:
Recursive CTEA Recursive CTE is a CTE that calls *itself* during execution, looping until it hits a stop condition.
Simple Definition
A Recursive CTE is a CTE that calls itself to build hierarchical or recursive query results.
Why Are Recursive CTEs Needed?
Picture a company org chart:
You want to:
Show Entire Organization HierarchyA basic SELECT won't cut it. Recursive CTEs solve this.
How Recursive CTE Works
A Recursive CTE has two parts:
Anchor Query
+
Recursive QueryAnchor Query
The starting point. It returns your initial rows.
Example:
CEORecursive Query
Calls the CTE itself. Finds the next batch of 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
Kicks off the CTE.
Anchor Query
Your starting result set.
UNION ALL
Combines results from both parts.
Recursive Query
The part that calls the CTE itself.
Final SELECT
Shows all generated rows.
Simple Number Generation Example
Let's generate:
1 To 5
Recursive 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 5
Step-by-Step Execution
First pass (anchor):
SELECT 1Output:
1
Second pass (recursive):
1 + 1Output:
2
Third pass:
2 + 1Output:
3
Keeps going 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
Get the entire 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 Neha
Boom. Hierarchy pulled automatically.
Organization Chart Example
Your structure:
A Recursive CTE pulls the entire reporting structure in one query.
Folder Structure Example
Your directory tree:
Recursive CTE traverses all nested folders.
Product Category Example
Your category tree:
Recursive query pulls the complete tree.
University Example
Course prerequisites:
Programming Basics
↓
Data Structures
↓
Algorithms
↓
Advanced AlgorithmsRecursive CTE retrieves prerequisite chains.
Banking Example
Branch structure:
Head Office
↓
Regional Office
↓
Branch OfficeRecursive queries display the hierarchy.
Understanding UNION ALL
Recursive CTEs almost always use:
UNION ALLWhy? Because:
Faster Preserves Duplicates Required For Recursion
Recursive Depth
Each execution creates a new level.
Example:
Level 1 CEO Level 2 Managers Level 3 Employees Level 4 Interns
Adding 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 Condition
Without it:
Infinite LoopWrong Example
WITH Numbers AS
(
SELECT 1
UNION ALL
SELECT Num + 1
FROM Numbers
)No stop condition. Result:
Infinite Recursion
Your DB will hate you.
Correct Example
WHERE Num < 5Stops it safely.
Recursive CTE vs Loop
Traditional programming:
FOR LOOP WHILE LOOP
SQL 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
Your main use case.
Cleaner Queries
Way more readable than multiple joins.
Dynamic Depth
Works with unknown hierarchy levels.
Reusable Logic
Easy to maintain and tweak.
Powerful Reporting
Great for analytics.
Disadvantages of Recursive CTEs
Performance Cost
Large hierarchies can get expensive.
Infinite Loop Risk
Missing stop conditions = bad time.
Memory Usage
Deep recursion eats resources.
Complexity
Harder if you're just starting out.
Common Mistakes
Missing Stop Condition
The biggest mistake.
Using UNION Instead of UNION ALL
Slower and unnecessary.
Deep Recursion
Might exceed your database's limits.
Poor Indexing
Hierarchy queries can drag if not indexed.
Best Practices
Always Include Stop Condition
Prevents infinite loops.
Use UNION ALL
Better performance.
Index Parent Columns
Makes recursive joins faster.
Limit Recursion Depth
Protect your server.
Test Large Hierarchies
See how it performs before going live.
Common Interview Questions
What is a Recursive CTE?
A CTE that calls itself.
What are the two parts of a Recursive CTE?
Anchor Query
Recursive QueryWhy is UNION ALL used?
Combines recursive results efficiently.
What is the purpose of the stop condition?
Prevents infinite recursion.
Where are Recursive CTEs commonly used?
Hierarchies, org charts, category trees, and folder structures.
Summary
Recursive CTEs are powerful for processing hierarchical and recursive data. They have an anchor query that starts the process, and a recursive query that keeps going until you tell it to stop.
In this lesson, you learned:
- What Recursive CTEs are
- Recursive CTE syntax
- Anchor Query basics
- Recursive Query basics
- Employee hierarchy examples
- Folder structure examples
- Product category trees
- Stop conditions
- Advantages and disadvantages
- Best practices
Mastering Recursive CTEs matters because hierarchical data shows up everywhere in real applications—org structures, reporting systems, nested categories, 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 Complete Guide topic.
Search Terms
sql-complete-guide, sql complete guide, sql, complete, guide, advanced, recursive, cte
Related SQL Complete Guide Topics