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] ) SELECT * FROM subordinates;The root nodes in a hierarchical table usually have parent_id IS NULL. This selects the top-level employees.
Complete the recursive part to join employees to their subordinates by matching parent_id to id.
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 ) SELECT * FROM subordinates;We join employees where their parent_id matches the id of the current subordinates to find the next level.
Fix the error in the recursive CTE by correctly aliasing the recursive table in the join.
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 [1] ON e.parent_id = subordinates.id ) SELECT * FROM subordinates;The recursive CTE must join to its own alias, which is subordinates here, not the base table.
Fill both blanks to add a level column that increments with each recursion and start it at 1.
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;
We add a level column starting at 1 for root nodes and increment it by 1 for each recursion to track depth.
Fill all three blanks to select id, name, and level from the recursive CTE 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 [1], [2], [3] FROM subordinates ORDER BY level ASC;
The final SELECT chooses id, name, and level columns and orders results by level ascending to show hierarchy levels.