Intermediatecomparison
ROW_NUMBER vs RANK vs DENSE_RANK, and how do you find the second highest salary per department?
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
See the concept: Join fan-outWhy a join to a one-to-many table multiplies sums
Join fan-out
| O101 | line 1 | ₹300 |
| O101 | P101 | FAILED |
| O101 | P102 | SUCCESS |
| line 1 | P101 | ₹300 |
| line 1 | P102 | ₹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
Key points
- tie handling
- PARTITION BY
- DENSE_RANK for Nth value