SQL Recursive CTE Explained: Step-by-Step Tutorial with Use Cases

Common Table Expressions (CTEs) are an essential feature in SQL that simplify complex queries and enhance readability. Among them, Recursive CTEs are particularly powerful, enabling us to work with hierarchical data, generate sequences, and solve problems that require recursion within SQL queries.
In this blog, we will explore Recursive CTEs in depth, covering their syntax, use cases, benefits, and practical examples.
A Recursive CTE (Common Table Expression) is a special type of CTE that refers to itself within the query. It is commonly used to work with hierarchical data such as organizational structures, file systems, or tree-like relationships in databases.
A recursive CTE has two main components:
The syntax of a Recursive CTE in SQL follows this structure:
WITH Recursive_CTE (column1, column2, ...) AS (
-- Anchor Query (Base Case)
SELECT column1, column2, ...
FROM Table_Name
WHERE condition
UNION ALL
-- Recursive Query (Recursive Member)
SELECT column1, column2, ...
FROM Table_Name
INNER JOIN Recursive_CTE
ON Table_Name.parent_id = Recursive_CTE.id
)
SELECT * FROM Recursive_CTE;
Let’s consider an Employee table where each employee has a manager_id
, forming a hierarchical structure.
Employee_ID | Employee_Name | Manager_ID |
---|---|---|
1 | Alice | NULL |
2 | Bob | 1 |
3 | Charlie | 1 |
4 | David | 2 |
5 | Eve | 2 |
6 | Frank | 3 |
In this table:
Manager_ID
is NULL).We can use a Recursive CTE to retrieve the hierarchy of employees reporting to a specific manager.
WITH EmployeeHierarchy AS (
-- Base Case: Select the top-level manager (Alice)
SELECT Employee_ID, Employee_Name, Manager_ID, 1 AS Level
FROM Employee
WHERE Manager_ID IS NULL
UNION ALL
-- Recursive Case: Fetch employees reporting to the previous level
SELECT e.Employee_ID, e.Employee_Name, e.Manager_ID, eh.Level + 1
FROM Employee e
INNER JOIN EmployeeHierarchy eh
ON e.Manager_ID = eh.Employee_ID
)
SELECT * FROM EmployeeHierarchy;
Employee_ID | Employee_Name | Manager_ID | Level |
---|---|---|---|
1 | Alice | NULL | 1 |
2 | Bob | 1 | 2 |
3 | Charlie | 1 | 2 |
4 | David | 2 | 3 |
5 | Eve | 2 | 3 |
6 | Frank | 3 | 3 |
Here, we have successfully retrieved the hierarchy with the level of each employee.
Recursive CTEs are widely used in various scenarios, including:
We can use a Recursive CTE to generate a sequence of numbers from 1 to 10.
WITH Numbers AS (
SELECT 1 AS Num -- Base case
UNION ALL
SELECT Num + 1 FROM Numbers WHERE Num < 10 -- Recursive case
)
SELECT * FROM Numbers;
Num |
---|
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
This is a simple example demonstrating how recursion can generate sequences without using loops.
While Recursive CTEs are powerful, they can lead to performance issues if not optimized properly. Here are some optimization techniques:
OPTION (MAXRECURSION n)
to Limit Recursion DepthSQL Server allows a default recursion depth of 100, but you can increase or decrease it.
OPTION (MAXRECURSION 50);
This prevents infinite loops caused by incorrect recursive conditions.
Fetching unnecessary records increases recursion depth. Apply filters at the Anchor Query stage.
If dealing with very deep hierarchical data, consider:
Manager_ID
).If the Recursive Member does not converge to a stopping condition, it will cause an infinite loop.
WHERE Num < 10
in the sequence example).MAXRECURSION
to limit iterations.Recursive queries can become slow, especially with large datasets.
Supports Recursive CTEs with WITH RECURSIVE
.
Uses WITH RECURSIVE
for recursive queries.
Supports recursive queries via CONNECT BY PRIOR
and WITH RECURSIVE
.
Recursive CTEs are a powerful SQL feature for handling hierarchical data and generating sequences. By understanding their structure, use cases, and optimizations, you can leverage recursion effectively in your queries.
✅ Recursive CTEs consist of an Anchor Query and a Recursive Member
✅ Useful for hierarchical data, graph traversal, and sequence generation
✅ Optimization is crucial to avoid performance issues
✅ Supported in SQL Server, PostgreSQL, MySQL, and Oracle
Mastering Recursive CTEs will improve your SQL skills and help you efficiently manage hierarchical data. Try out these queries in your database and see the power of recursion in action!