Complete the code to start a recursive CTE with the base query.
WITH RECURSIVE cte AS (SELECT id, parent_id FROM employees WHERE parent_id IS [1])The base query selects rows where parent_id is NULL, which usually means top-level employees without a manager.
Complete the recursive part to join the CTE with the employees table.
SELECT id, parent_id FROM employees UNION ALL SELECT e.id, e.parent_id FROM employees e JOIN cte ON e.parent_id = cte.[1]The recursive part joins employees where their parent_id matches the id from the CTE, to find children.
Fix the error in the recursive CTE by completing the anchor member.
WITH RECURSIVE cte AS (SELECT id, parent_id FROM employees WHERE [1]) SELECT * FROM cte;id = 0 may not match any rows.parent_id = id causes a wrong condition.id IS NULL is usually false for primary keys.The anchor member must select the root rows where parent_id is NULL to start recursion properly.
Fill both blanks to complete the recursive CTE that finds all descendants of employee 5.
WITH RECURSIVE descendants AS (SELECT id, parent_id FROM employees WHERE id = [1] UNION ALL SELECT e.id, e.parent_id FROM employees e JOIN descendants d ON e.[2] = d.id) SELECT * FROM descendants;
e.id = d.id causes no recursion.e.employee_id which is not a valid column.The anchor selects employee with id = 5. The recursive part joins on e.parent_id = d.id to find children.
Fill all three blanks to create a recursive CTE that calculates the depth level of each employee in the hierarchy.
WITH RECURSIVE hierarchy AS (SELECT id, parent_id, 1 AS level FROM employees WHERE parent_id IS [1] UNION ALL SELECT e.id, e.parent_id, h.level [2] 1 FROM employees e JOIN hierarchy h ON e.parent_id = h.[3]) SELECT * FROM hierarchy;
parent_id IS NOT NULL in anchor selects wrong rows.- instead of + decreases level incorrectly.parent_id instead of id.The anchor selects root employees with parent_id IS NULL. The recursive part increments the level by 1 and joins on h.id.