InterviewPrepKit

Home / SQL / Subqueries & CTEs

Salaries Above the Company Average

medium
Solving tips
  • A scalar subquery returns exactly one row and one column, so it can stand in wherever a single value is expected — inside SELECT or on the right of a WHERE comparison.
  • The subquery `(SELECT AVG(salary) ...)` runs once for the whole statement, not once per row, because it does not reference the outer query.
  • AVG over an integer column returns numeric in PostgreSQL, so cast if you want a clean integer difference.

Find every employee who earns more than the company-wide average salary, and show how far above the average they are.

Schema

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

Sample data — employees:

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

Task

Return the name, the salary, and a column above_avg equal to the employee’s salary minus the company-wide average salary (as an integer), for every employee whose salary is strictly greater than that average.

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

Expected output

The six salaries sum to 480000, so the company average is 80000.

namesalaryabove_avg
Eve12000040000
Carol10000020000
Alice9000010000
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.