datarekha
SQL Medium Asked at AmazonAsked at MetaAsked at Google

How do you find the second-highest salary in SQL?

The short answer

Rank salaries with DENSE_RANK() ordered descending and keep rank 2 — it handles duplicate salaries and generalises to the Nth-highest. A correlated subquery (the max salary strictly below the overall max) also works, while LIMIT 1 OFFSET 1 is only safe when no two people share a salary.

How to think about it

The interviewer is really checking two things: do you reach for a window function, and do you handle ties correctly. Most candidates write LIMIT 1 OFFSET 1 and quietly get it wrong.

The robust answer — DENSE_RANK

SELECT salary
FROM (
  SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
  FROM employees
) ranked
WHERE rnk = 2;

DENSE_RANK assigns 1 to the highest salary, 2 to the next distinct salary, and never skips a number when values tie. Change rnk = 2 to rnk = N and you have the Nth-highest with no rewrite — which is exactly the follow-up they ask next.

salaryDENSE_RANKRANKROW_NUMBER500111400222400223300344
Two people earn 400. Only DENSE_RANK keeps the next distinct salary (300) at rank 3.

Run it yourself — try swapping rnk = 2 for rnk = 3 to get the third-highest, or add a duplicate salary to see why DENSE_RANK stays correct:

The no-window-function answer

If they ban window functions (common for older MySQL or to test fundamentals):

SELECT MAX(salary) AS second_highest
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);

This reads cleanly as “the largest salary that is below the largest salary.” It returns NULL rather than an error when there is no second salary — which many interviewers consider the correct behaviour, and a good thing to mention out loud.

What to say out loud

  • Lead with DENSE_RANK and note it generalises to the Nth-highest.
  • Mention the tie behaviour explicitly — that is the whole point of the question.
  • Confirm the empty/NULL case: what should the query return if everyone earns the same salary?
Learn it properly Window functions

Keep practising

All SQL questions

Explore further

Skip to content