Bird
0
0

Given the table Employees(id, manager_id) and this recursive CTE:

medium📝 query result Q13 of 15
SQL - Common Table Expressions (CTEs)
Given the table Employees(id, manager_id) and this recursive CTE:
WITH RECURSIVE EmpCTE AS (
  SELECT id, manager_id FROM Employees WHERE id = 1
  UNION ALL
  SELECT e.id, e.manager_id FROM Employees e JOIN EmpCTE c ON e.manager_id = c.id
)
SELECT id FROM EmpCTE ORDER BY id;

What does this query return?
AAll employees who have no manager
BAll employees who report directly or indirectly to employee with id 1
COnly the employee with id 1
DAll employees in the table
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the anchor query

    The anchor selects employee with id = 1.
  2. Step 2: Analyze the recursive part

    The recursive part joins Employees where manager_id matches the id from previous results, thus finding direct reports, then their reports, and so on.
  3. Final Answer:

    All employees who report directly or indirectly to employee with id 1 -> Option B
  4. Quick Check:

    Recursive CTE finds all subordinates under id 1 [OK]
Quick Trick: Recursive join on manager_id finds all reports [OK]
Common Mistakes:
  • Thinking it returns only the anchor row
  • Assuming it returns employees without managers
  • Believing it returns all employees regardless of manager

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More SQL Quizzes