SteelReed

Search

Search posts, questions…

SQL & Query TuningQuestion 16 / 37

Middle

Write SQL for the second (or Nth) highest salary, handling ties and returning NULL if none?

Short answer

Take the distinct salaries, sort descending, skip the first N−1 and take one: SELECT DISTINCT salary ... ORDER BY salary DESC LIMIT 1 OFFSET N-1, wrapped in a scalar subquery so a missing level gives NULL. The more general approach is DENSE_RANK().

level existsnot enough levelsSalaries: 100, 100, 90DISTINCT: 100, 90ORDER BY DESCOFFSET 1 LIMIT 1Result: 90Scalar subqueryreturns NULL

3 points to say:

  1. DISTINCT + ORDER BY DESC + OFFSET N-1, wrapped in a scalar subquery so fewer than N levels gives NULL instead of no rows.
  2. DENSE_RANK handles ties and extends to per-group; ROW_NUMBER and RANK are wrong with ties.
  3. With NULL salaries, filter NULL or use NULLS LAST; an index on salary means reading only the first few entries.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.