ExpertCTEs & Recursion50 points

Span of control: who really runs the org?

Nordvik Global has a deep reporting tree: the CEO, vice presidents, directors, managers and individual contributors. Management wants to know each leader's full span, not just direct reports: everyone who reports to them directly or through any number of levels below. Only active employees (termination_date empty) are part of anyone's span.

Task: with a recursive CTE return one row per person who has at least one active report: manager (name), direct_reports, total_reports (direct and indirect) and levels_below (how many reporting levels sit under the manager, 1 if they only have direct reports). Sort by total_reports from high to low, then manager A to Z.

The data you can query

Each table is shown with its column types and the first rows, so you can see exactly what the data looks like.

departments7 rows
dept_id INTEGERname TEXT
1Engineering
2Sales
3Finance
4People & Culture
5Marketing
6Operations

Showing the first 6 of 7 rows.

employees58 rows
emp_id INTEGERname TEXTdept_id INTEGERjob_title TEXTcountry TEXTgrade INTEGERsalary_usd INTEGERhire_date TEXTtermination_date TEXTmanager_id INTEGER
1Harry Clarke7Chief Executive OfficerUnited Kingdom93750002016-03-01NULLNULL
2Khalid Al Hashimi1VP of EngineeringUnited Arab Emirates82370002021-03-01NULL1
3Zainab Ahmed1Director of Engineering 1Pakistan7590002021-10-12NULL2
4Hina Khan1Engineering ManagerPakistan6400002024-08-10NULL3
5Ren Tanaka1QA EngineerJapan4680002022-12-19NULL4
6Piotr Zielinski1Data EngineerPoland3330002025-10-23NULL4

Showing the first 6 of 58 rows.

performance_reviews178 rows
review_id INTEGERemp_id INTEGERreview_period TEXTrating INTEGERreviewed_on TEXT
122024-H222024-12-20
222025-H112025-06-18
322025-H232025-12-30
422026-H122026-06-25
532024-H232024-12-29
632025-H142025-06-18

Showing the first 6 of 178 rows.

promotions9 rows
promo_id INTEGERemp_id INTEGERpromo_date TEXTold_grade INTEGERnew_grade INTEGERold_salary_usd INTEGERnew_salary_usd INTEGER
132025-11-26675000059000
242025-12-10563300040000
362026-05-08232800033000
472025-09-1467120000143000
5122025-01-06232700029000
6292026-02-23678000091000

Showing the first 6 of 9 rows.

Your query runs on SQLite. Write a single SELECT; use LIMIT instead of TOP.

Need a hint?

Seed the recursion with (manager, direct report, depth 1), then keep joining the reports of the last person found while carrying the original manager along.