InterviewPrepKit

Home / SQL / Subqueries & CTEs

Earning More Than Your Department Average

medium
Solving tips
  • A correlated subquery references a column from the outer query, so it is re-evaluated once per outer row — here, once per employee, against that employee's own department.
  • Alias the outer and inner tables differently (e.g. `e` and `e2`) so the correlation condition `e2.department_id = e.department_id` is unambiguous.
  • The comparison is strictly greater than the group average, so an employee sitting exactly at their department average is excluded.

Find every employee who earns strictly more than the average salary of their own department.

Schema

CREATE TABLE employees (
    id            integer PRIMARY KEY,
    name          text    NOT NULL,
    department_id integer NOT NULL,
    salary        integer NOT NULL
);

Sample data — employees:

idnamedepartment_idsalary
1Alice1090000
2Bob1060000
3Carol20100000
4Dave2055000
5Eve30120000
6Frank3055000
7Grace2065000

Task

Return the name, department_id, and salary of every employee whose salary is strictly greater than the average salary of the department they belong to.

Order by department_id ascending, then by salary descending. Expected columns: name, department_id, salary.

Expected output

Department averages: dept 10 = 75000, dept 20 = (100000 + 55000 + 65000) / 3 ≈ 73333.33, dept 30 = 87500.

namedepartment_idsalary
Alice1090000
Carol20100000
Eve30120000
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.