Complete the code to start the recursive CTE by selecting the root nodes (where parent_id is NULL).
WITH RECURSIVE subordinates AS (
SELECT id, name, parent_id
FROM employees
WHERE parent_id IS [1]
)The root nodes in a hierarchical table usually have parent_id as NULL. So the base case selects rows where parent_id IS NULL.
Complete the recursive part to join the CTE with the employees table to find subordinates.
WITH RECURSIVE subordinates AS (
SELECT id, name, parent_id
FROM employees
WHERE parent_id IS NULL
UNION ALL
SELECT e.id, e.name, e.parent_id
FROM employees e
JOIN subordinates s ON e.[1] = s.id
)The recursive step joins employees where their parent_id matches the id of the current subordinates, thus finding direct reports.
Fix the error in the final SELECT statement to get all subordinates' names.
WITH RECURSIVE subordinates AS (
SELECT id, name, parent_id
FROM employees
WHERE parent_id IS NULL
UNION ALL
SELECT e.id, e.name, e.parent_id
FROM employees e
JOIN subordinates s ON e.parent_id = s.id
)
SELECT [1] FROM subordinates;The question asks for all subordinates' names, so selecting the name column is correct.
Fill both blanks to add a level column showing depth in the hierarchy and increment it in recursion.
WITH RECURSIVE subordinates AS ( SELECT id, name, parent_id, 1 AS [1] FROM employees WHERE parent_id IS NULL UNION ALL SELECT e.id, e.name, e.parent_id, s.[2] + 1 FROM employees e JOIN subordinates s ON e.parent_id = s.id ) SELECT * FROM subordinates;
The column name must be consistent in both parts of the CTE. Here, level is used to track depth, so both blanks should be level.
Fill all three blanks to filter subordinates at level greater than 2 and order by level ascending.
WITH RECURSIVE subordinates AS ( SELECT id, name, parent_id, 1 AS level FROM employees WHERE parent_id IS NULL UNION ALL SELECT e.id, e.name, e.parent_id, s.level + 1 FROM employees e JOIN subordinates s ON e.parent_id = s.id ) SELECT name, level FROM subordinates WHERE level [1] 2 ORDER BY level [2]; -- Use [3] to specify ascending order
To get subordinates deeper than level 2, use level > 2. To order ascending, use ORDER BY level ASC. The third blank clarifies the order direction as ASC.