Bird
0
0

You have a table employees(id INT, manager_id INT) representing a company hierarchy. How would you write a recursive CTE to find all employees under manager with id = 10, including indirect reports?

hard📝 Application Q15 of 15
PostgreSQL - Common Table Expressions
You have a table employees(id INT, manager_id INT) representing a company hierarchy. How would you write a recursive CTE to find all employees under manager with id = 10, including indirect reports?
A<pre>WITH RECURSIVE subordinates AS ( SELECT id FROM employees WHERE manager_id = 10 UNION ALL SELECT e.id FROM employees e JOIN subordinates s ON e.manager_id = s.id ) SELECT * FROM subordinates;</pre>
B<pre>WITH RECURSIVE subordinates AS ( SELECT id FROM employees WHERE id = 10 UNION ALL SELECT e.id FROM employees e JOIN subordinates s ON e.id = s.manager_id ) SELECT * FROM subordinates;</pre>
C<pre>WITH RECURSIVE subordinates AS ( SELECT id FROM employees WHERE manager_id = 10 UNION ALL SELECT e.manager_id FROM employees e JOIN subordinates s ON e.id = s.id ) SELECT * FROM subordinates;</pre>
D<pre>WITH RECURSIVE subordinates AS ( SELECT id FROM employees WHERE manager_id = 10 UNION ALL SELECT e.id FROM employees e JOIN subordinates s ON e.id = s.manager_id ) SELECT * FROM subordinates;</pre>
Step-by-Step Solution
Solution:
  1. Step 1: Identify the anchor query

    The anchor selects employees directly reporting to manager 10: WHERE manager_id = 10.
  2. Step 2: Understand the recursive join

    The recursive part joins employees whose manager_id matches any previously found employee id, thus finding indirect reports.
  3. Final Answer:

    WITH RECURSIVE subordinates AS ( SELECT id FROM employees WHERE manager_id = 10 UNION ALL SELECT e.id FROM employees e JOIN subordinates s ON e.manager_id = s.id ) SELECT * FROM subordinates; -> Option A
  4. Quick Check:

    Join on e.manager_id = s.id to find subordinates [OK]
Quick Trick: Join on manager_id = previous employee id to find reports [OK]
Common Mistakes:
  • Swapping join conditions (id vs manager_id)
  • Starting anchor with wrong WHERE clause
  • Selecting wrong columns in recursive part

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes