advancedTop 30 Scenario-Based Questions

How would you find all employees in a reporting hierarchy under a specific manager (any depth)?

WITH RECURSIVE subordinates AS (-- Anchor: direct reports of manager with id=1 SELECT emp_id, first_name, manager_id, 1 AS level FROM employees WHERE manager_id = 1 UNION ALL -- Recursive: find reports of reports SELECT e.emp_id, e.first_name, e.manager_id, s.level + 1 FROM employees e JOIN subordinates s ON e.manager_id = s.emp_id WHERE s.level < 10 -- safety limit) SELECT emp_id, first_name, lev

This is a Pro chapter

Sign in, then upgrade to Pro or Power to unlock this and the full Databases Mastery library.

How would you find all employees in a reporting hierarchy under a specific manager (any depth)?

Next Step

Continue to Your PostgreSQL table has 40% dead tuples causing slow queries. How do you fix it with no downtime?← Back to all SQL questions