advancedCTEs — Common Table Expressions & Recursive CTEs

You need to find all subordinates of a manager at ANY level (5 levels deep in some paths). Write the SQL.

WITH RECURSIVE subordinates AS (-- Anchor: start with the target manager SELECT emp_id, first_name, manager_id, 0 AS level FROM employees WHERE emp_id = 1 -- Alice (find all her reports) UNION ALL -- Recursive: find all direct reports of each person in the CTE 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

Ready to master this question?

Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.

Sign in to generate a response

Next Step

Continue to How do you read an EXPLAIN ANALYZE output? What are the key things to look for?← Back to all SQL questions