InterviewPrepKit

Home / SQL / Subqueries & CTEs

Nth Highest Salary

medium
Solving tips
  • Ranking must be over DISTINCT salary values, so two people paid the same amount share a rank — `DENSE_RANK()` does exactly this, unlike `ROW_NUMBER()` or `RANK()`.
  • Wrap the lookup in a scalar subquery so that when fewer than N distinct salaries exist the result is a single NULL row rather than an empty result set.
  • The `LIMIT 1 OFFSET N-1` trick works only after `SELECT DISTINCT ... ORDER BY salary DESC`, and it too returns no row (not NULL) unless wrapped.

Return the third-highest distinct salary. If there are fewer than three distinct salaries, return NULL.

Schema

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

Sample data — employees:

idnamesalary
1Alice100
2Bob90
3Carol90
4Dave80
5Eve70
6Frank70

Task

Return a single column named nth_highest_salary containing the third-highest distinct salary (N = 3). Duplicate salaries count once. If fewer than three distinct salaries exist, the query must return one row whose value is NULL.

Expected column: nth_highest_salary.

Expected output

Distinct salaries in descending order are 100, 90, 80, 70; the third is 80.

nth_highest_salary
80
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.