Skip to main content
Intermediatecomparison

ROW_NUMBER vs RANK vs DENSE_RANK, and how do you find the second highest salary per department?

Source: PostgreSQL: SELECT (clause processing)

Quick answer

ROW_NUMBER gives unique numbers even for ties; RANK gives ties the same number and skips (1,1,3); DENSE_RANK gives ties the same number without gaps (1,1,2).

ROW_NUMBER gives unique numbers even for ties; RANK gives ties the same number and skips (1,1,3); DENSE_RANK gives ties the same number without gaps (1,1,2). For "second highest salary" use DENSE_RANK partitioned by department ordered by salary DESC and keep rank 2, so duplicate top salaries do not hide the second value.

Animated explanation

ROW_NUMBER

  • 1, 2, 3
  • Ties get different numbers

RANK

  • 1, 1, 3
  • Ties share, then a gap

DENSE_RANK

  • 1, 1, 2
  • Ties share, no gap
  • Use for the Nth highest value
Salaries 900, 900, 800: only DENSE_RANK gives 800 rank 2.
See the concept: Join fan-outWhy a join to a one-to-many table multiplies sums
Join fan-out
order_lines: one row per line
O101line 1₹300
payments: one row per attempt
O101P101FAILED
O101P102SUCCESS
lines JOIN payments ON order_id
line 1P101₹300
line 1P102₹300
SUM(line_revenue)₹600

Wrong: the single ₹300 line is counted once per payment attempt.

Fix: aggregate payments to one row per order first

line 1, paid, ₹300, so SUM = ₹300

One order line, two payment attempts: a direct join doubles the revenue. Aggregating payments to order grain first keeps one row per line.

Key points

  • tie handling
  • PARTITION BY
  • DENSE_RANK for Nth value

References

Discussion