ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Recursive CTE for Hierarchical Data Traversal

SQL MySQL

Goal -- WPM

Ready
Exercise Algorithm Area
1WITH RECURSIVE EmployeeHierarchy AS (
2-- Anchor Member: Select the top-level employee(s)
3SELECT
4employee_id,
5employee_name,
6manager_id,
70 AS level
8FROM
9employees
10WHERE
11manager_id IS NULL -- Assuming top-level employees have no manager
12
13UNION ALL
14
15-- Recursive Member: Select employees whose manager is in the previous iteration
16SELECT
17e.employee_id,
18e.employee_name,
19e.manager_id,
20eh.level + 1
21FROM
22employees e
23JOIN
24EmployeeHierarchy eh ON e.manager_id = eh.employee_id
25WHERE
26eh.level < 10 -- Safety break to prevent infinite recursion in case of cycles
27)
28-- Select all employees and their hierarchy level
29SELECT
30employee_id,
31employee_name,
32manager_id,
33level
34FROM
35EmployeeHierarchy
36ORDER BY
37level,
38employee_id;
39
40-- Sample Schema and Data (for context, not part of the CTE itself):
41/*
42CREATE TABLE employees (
43employee_id INT PRIMARY KEY,
44employee_name VARCHAR(100) NOT NULL,
45manager_id INT NULL,
46FOREIGN KEY (manager_id) REFERENCES employees(employee_id)
47);
48
49INSERT INTO employees (employee_id, employee_name, manager_id)
50VALUES
51(1, 'Alice CEO', NULL),
52(2, 'Bob VP Eng', 1),
53(3, 'Charlie VP Sales', 1),
54(4, 'David Eng Lead', 2),
55(5, 'Eve Engineer', 4),
56(6, 'Frank Sales Lead', 3),
57(7, 'Grace Sales Rep', 6);
58*/
59
60-- The `WHERE eh.level < 10` clause in the recursive member acts as a safeguard.
61-- In a real-world scenario with potentially cyclic data, more robust cycle detection
62-- might be needed, e.g., by tracking visited nodes or using a path column.
63-- However, for typical organizational hierarchies, this level limit is often sufficient
64-- to prevent runaway queries and indicates a data integrity issue if hit.
Algorithm description viewbox

Recursive CTE for Hierarchical Data Traversal

Algorithm description:

This scenario demonstrates how to use a recursive Common Table Expression (CTE) in MySQL to query hierarchical data, such as an organizational chart. Recursive CTEs are essential for tasks like finding all subordinates of a manager, calculating path lengths in a tree, or performing multi-level aggregations. They allow for elegant solutions to problems that would otherwise require complex iterative logic or self-joins.

Algorithm explanation:

A recursive CTE consists of an anchor member (the base case) and a recursive member (the step that calls itself). The anchor member `SELECT`s the starting rows (e.g., top-level employees). The recursive member `SELECT`s rows that are related to the results of the previous iteration, joining the `employees` table with the CTE itself (`EmployeeHierarchy`). The `UNION ALL` combines the results. The recursion stops when the recursive member returns no rows. A `level` column is added to track the depth. The `WHERE eh.level < 10` clause acts as a safety termination condition to prevent infinite loops in case of data cycles, limiting the recursion depth to 10. Time complexity can vary greatly depending on the depth and breadth of the hierarchy, potentially O(N) where N is the number of nodes visited. Space complexity is also O(N) for storing the intermediate results of the CTE.

Pseudocode:

1. Define a recursive CTE named `EmployeeHierarchy`.
2. Anchor Member: Select employees with `manager_id` IS NULL, assign `level` 0.
3. Recursive Member: Join `employees` table with `EmployeeHierarchy` on `e.manager_id = eh.employee_id`.
4. Increment `level` by 1 in the recursive member.
5. Add a termination condition (e.g., `eh.level < max_depth`) to the recursive member.
6. Combine anchor and recursive members using `UNION ALL`.
7. Select all columns from `EmployeeHierarchy`.
8. Order the final result by `level` and `employee_id`.