All problems

Who Manages Someone Else?

hardSQLSubqueries

IT at Kestrel Labs is switching on manager-only screens in the new HR portal, and needs the list of people who should get them. There is no is_manager flag anywhere in the database and no separate table of managers. Being a manager is not something recorded about a person — it is something that shows up because other people point at them.

Each employee row carries a manager_id, the id of the person they report to, left empty for anyone who reports to nobody. So the names IT wants are hidden in that column, written as numbers, on rows belonging to other people entirely. Note also that a manager with three reports is pointed at three times and must still appear once on the list, and that team leads who happen to lead nobody are not managers for this purpose.

employees — one row per person. manager_id is the id of that person's own manager, or NULL if they have none.

id name department_id salary hire_date manager_id
1 Ava Chen 1 145000 2021-03-14 NULL
2 Ben Ortiz 1 118000 2022-06-01 1
3 Cara Novak 1 121000 2023-01-10 1
4 Deshawn Lee 2 95000 2020-09-23 NULL
5 Elin Kask 2 88000 2022-11-05 4
6 Farid Amiri 3 76000 2023-04-18 NULL
7 Grace Kim 4 132000 2021-07-30 NULL
8 Hugo Silva 4 110000 2023-02-14 7
9 Ines Duarte 4 104000 2023-08-01 7
10 Jonas Weber 2 91000 2021-12-19 4

The table already exists in the database — there is nothing to create or load.

Task: Write a query returning a single column, name, holding every employee who is pointed at as somebody else's manager. Each such person appears exactly once, however many reports they have. Anyone who leads nobody is absent, including employees whose own manager_id is NULL. Hand the rows back alphabetically by name.

Example output — shape only, on invented names.

name
Anton Reis
Rosa Kwan
Yusuf Bello

Sign in to solve this problem

Reading problems is free for everyone — solving them (Run, Submit, and tracking what you've solved) needs an account.

Sign in

Discussion

Sign in to join the discussion — reading is open to everyone.

Loading comments…