DEV Community

Pranav Bakare
Pranav Bakare

Posted on

Recursive Common Table Expression (CTE) PART 1

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:

  1. Anchor member: The base query that initializes the recursion.

  2. 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
Enter fullscreen mode Exit fullscreen mode

)
-- Now select from the CTE
SELECT * FROM EmployeeHierarchy;

Explanation:

  1. Anchor member: Retrieves the top-most employee(s) (where ManagerID is NULL, i.e., Alice).

  2. 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.

  3. Final result: Lists the entire hierarchy starting from Alice.

Output:

This approach can be adapted to many other scenarios requiring recursive data traversal.

Top comments (0)