Employees earning more than their managers
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
Each employee in employees may have a manager, who is also an employee (manager_id points to their id).
Write a query that returns the names of employees who earn strictly more than their manager, in a column named employee. Rows can be returned in any order.
Example
employees
| id | name | salary | manager_id |
|---|---|---|---|
| 1 | Noa | 70000 | 3 |
| 2 | Avi | 80000 | 4 |
| 3 | Dana | 60000 | NULL |
| 4 | Yossi | 90000 | NULL |
Result:
| employee |
|---|
| Noa |
Noa earns 70000 and Noa's manager, Dana, earns 60000. Avi earns less than Yossi.
Tip
You need two rows from the same table side by side. Can you join a table to itself?
Schema
CREATE TABLE employees (
id INT PRIMARY KEY,
name TEXT NOT NULL,
salary INT NOT NULL,
-- NULL for employees without a manager.
manager_id INT REFERENCES employees (id)
);Approach
A self join: the same table twice, under two aliases. e is the employee and m is their manager:
SELECT e.name AS employee
FROM employees e
JOIN employees m ON m.id = e.manager_id
WHERE e.salary > m.salary;An INNER JOIN drops employees with no manager, which is what we want: there is nothing to compare them with. The aliases are what make this readable. Without them you can't tell which salary is whose.
A correlated subquery
The same thing, row by row:
SELECT name AS employee
FROM employees e
WHERE salary > (SELECT salary FROM employees m WHERE m.id = e.manager_id);When manager_id is NULL the subquery returns NULL, the comparison is UNKNOWN, and the row is dropped. The join version is usually easier to read and to extend, for example to return the manager's name too.
Follow-ups
- Whole management chain (anyone above them, not only their direct manager): that needs a recursive CTE,
WITH RECURSIVE. - Index
manager_idso finding someone's reports doesn't scan the table.
Reference solution
SELECT e.name AS employee
FROM employees e
JOIN employees m ON m.id = e.manager_id
WHERE e.salary > m.salary;