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().
3 points to say:
DISTINCT+ORDER BY DESC+OFFSET N-1, wrapped in a scalar subquery so fewer than N levels gives NULL instead of no rows.DENSE_RANKhandles ties and extends to per-group;ROW_NUMBERandRANKare wrong with ties.- With NULL salaries, filter NULL or use
NULLS LAST; an index onsalarymeans 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.