Recursive Common Table Expression (CTE) PART 1
Pranav Bakare
Posted on October 12, 2024
A Recursive Common Table Expression (CTE) is a CTE that references itself. It allows you to perform recursive queries, often used for hierarchical or tree-like data structures (e.g., organizational charts, folder structures, or graphs). A recursive CTE consists of two parts:
Anchor member: The base query that initializes the recursion.
Recursive member: A query that references the CTE itself to continue building the result set.
Example: Find a Hierarchy (e.g., Employee Management Tree)
Assume you have an employees table:
The goal is to recursively retrieve all employees under a particular manager. Here's how to do it using a recursive CTE:
WITH RECURSIVE EmployeeHierarchy AS (
-- Anchor member: get the top-level manager (e.g., Alice)
SELECT EmployeeID, Name, ManagerID
FROM employees
WHERE ManagerID IS NULL -- Adjust this condition based on your need
UNION ALL
-- Recursive member: get employees who report to the manager found in the previous step
SELECT e.EmployeeID, e.Name, e.ManagerID
FROM employees e
INNER JOIN EmployeeHierarchy eh ON e.ManagerID = eh.EmployeeID
)
-- Now select from the CTE
SELECT * FROM EmployeeHierarchy;
Explanation:
Anchor member: Retrieves the top-most employee(s) (where ManagerID is NULL, i.e., Alice).
Recursive member: Joins the employees table with the result of the previous step to find all employees that report to the top-level manager, and so on.
Final result: Lists the entire hierarchy starting from Alice.
Output:
This approach can be adapted to many other scenarios requiring recursive data traversal.
Posted on October 12, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 30, 2024