Skip to content
Preptima
mediumCodingConceptEntryMidSenior

Write a query returning the second-highest salary in each department, then tell me what it does when two people tie for the top.

To get the second highest salary per department in SQL, rank employees inside each department with DENSE_RANK and filter rank two. DENSE_RANK handles ties where ROW_NUMBER or a global MAX gives the wrong result. Use this window functions answer to show the decision, trade-off, and evidence rather than a memorised definition. It also connects sql queries to the point an interviewer is testing.

3 min readUpdated 2026-08-15

Answer

Short answer

Use DENSE_RANK() over partition by department order by salary desc, then keep rank = 2. That returns the second distinct salary per department and handles tied top salaries correctly.

Was this answer helpful?

Likely follow-ups

  • Rewrite it without window functions, using only a correlated subquery or a self-join.
  • Now return the Nth highest for a parameterised N. What changes?
  • How would you list departments that have no second-highest salary at all?
  • Given a table of invoice numbers with holes in it, find every missing range.

Related questions

Further reading