Skip to main content
04

Employees earning more than their managers

Easyself join

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

idnamesalarymanager_id
1Noa700003
2Avi800004
3Dana60000NULL
4Yossi90000NULL

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

sql
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:

sql
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:

sql
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_id so finding someone's reports doesn't scan the table.

Reference solution

sql
SELECT e.name AS employee
FROM employees e
JOIN employees m ON m.id = e.manager_id
WHERE e.salary > m.salary;