SQL fundamentals learning path Level 1 This level · 6 of 6
Easy postgresql sql

How do you find employees who earn more than their managers?

The 30 second answer

I join the employee table to itself, matching each employee's manager_id to the manager's id, and I keep the rows where the employee's salary is greater than the manager's. A LEFT JOIN with a WHERE on the manager's salary would drop employees who have no manager, which is usually what I want here, and an INNER JOIN does the same because those rows have no manager salary to compare.

Could you say this in an interview?

The table stores both the employee and the manager, so this is a self-join. One alias is the employee, the other is the manager, and the join condition is employee.manager_id = manager.id. The filter is then a comparison of the two salary columns.

CREATE TABLE employee (
    id         bigint PRIMARY KEY,
    name       text NOT NULL,
    salary     numeric NOT NULL,
    manager_id bigint REFERENCES employee (id)
);

INSERT INTO employee(id, name, salary, manager_id) VALUES
    (1, 'Sam',  90, NULL),
    (2, 'Alex', 80, 1),
    (3, 'Riley', 95, 1),
    (4, 'Quinn', 70, 2);

SELECT e.name  AS employee,
       e.salary AS employee_salary,
       m.name  AS manager,
       m.salary AS manager_salary
FROM employee e
JOIN employee m ON e.manager_id = m.id
WHERE e.salary > m.salary;

On that sample, only Riley earns more than Sam, so the result is one row: Riley 95, manager Sam 90. Alex earns less than Sam, and Quinn earns less than Alex. Sam has no manager, so the inner join drops that row, which is correct for this question.

A correlated subquery, WHERE salary > (SELECT salary FROM employee m WHERE m.id = e.manager_id), returns the same employees. The join is usually easier to extend if the interviewer then asks for the department or the gap.

Sources (2)
  1. PostgreSQL tutorial: Joins between tablespostgresql.org
  2. PostgreSQL: Table expressions and joined tablespostgresql.org
Previous
Next