Recursive Common Table Expressions (CTEs) in SQL enable the execution of recursive queries. These queries are useful when dealing with hierarchical or recursive data structures, such as organizational charts, bill of materials, or graph-like data. Recursive CTEs allow you to iteratively process data, repeatedly applying a query to its own output until a termination condition is met.
Syntax of Recursive CTEs:
The syntax for defining a recursive CTE consists of two parts: the base query and the recursive query.
sqlCopy code
WITH RECURSIVE cte_name (column1, column2, …)
AS (
— Base query
SELECT column1, column2, …
FROM initial_table
WHERE initial_condition
UNION ALL
— Recursive query
SELECT column1, column2, …
FROM cte_name
WHERE recursive_condition
)
SELECT *
FROM cte_name;
In the recursive CTE:
The base query defines the initial set of rows to start the recursion.
The recursive query repeatedly applies itself to its own output, using the previous result set as input.
The UNION ALL operator combines the results of the base and recursive queries.
The termination condition is specified in the recursive query by comparing the current rows with the previous ones.
Example:
Consider a table named Organization representing an organizational chart, with columns EmployeeID and ManagerID, where ManagerID points to the EmployeeID of the manager. We want to retrieve all employees who report directly or indirectly to a specific manager.
WITH RECURSIVE EmployeeHierarchy AS (
— Base query: Retrieve employees who directly report to the given manager
SELECT EmployeeID, ManagerID
FROM Organization
WHERE ManagerID = ‘manager_id’
UNION ALL
— Recursive query: Retrieve employees who report to the employees already in the hierarchy
SELECT o.EmployeeID, o.ManagerID
FROM Organization o
JOIN EmployeeHierarchy e ON o.ManagerID = e.EmployeeID
)
SELECT *
FROM EmployeeHierarchy;
In this example:
The base query selects the employees who report directly to the given manager.
The recursive query selects employees who report to the employees already in the hierarchy, building the hierarchy recursively.
The UNION ALL operator combines the results of the base and recursive queries.
The termination condition is implicitly specified by the absence of new rows to add to the hierarchy.
Recursive CTEs are a powerful feature in SQL, especially for handling hierarchical or recursive data structures in a concise and efficient manner.