What is the difference between ROW_NUMBER, RANK and DENSE_RANK?
EasyConceptSQL: Window Functions
Answer
All three number the rows of a window in the order given by its ORDER BY; they differ only in how they treat ties.
ROW_NUMBERgives every row a different number and breaks ties arbitrarily, unless you add a tie-breaking column.RANKgives tied rows the same rank and then skips numbers, leaving gaps (1, 2, 2, 4).DENSE_RANKgives tied rows the same rank without gaps (1, 2, 2, 3).- Use
ROW_NUMBERto pick exactly one row per group, such as each customer's latest order, andDENSE_RANKfor the nth highest distinct value.
Example:
SELECT name, salary,
ROW_NUMBER() OVER (ORDER BY salary DESC) AS rn,
RANK() OVER (ORDER BY salary DESC) AS rnk,
DENSE_RANK() OVER (ORDER BY salary DESC) AS drnk
FROM employees;
name | salary | rn | rnk | drnk
Asha | 900 | 1 | 1 | 1
Ravi | 800 | 2 | 2 | 2
Meera | 800 | 3 | 2 | 2
Kiran | 700 | 4 | 4 | 3
More in SQL: Window Functions
| # | Problem | Platform | Difficulty | Open | 1st1st Visit | 2nd2nd Visit | RevRevise |
|---|---|---|---|---|---|---|---|
| 1 | What is the difference between ROW_NUMBER, RANK and DENSE_RANK? | Concept | Easy | Read the answer to What is the difference between ROW_NUMBER, RANK and DENSE_RANK? | |||
| 2 | Rank Scores | LeetCode | Medium | Solve Rank Scores on LeetCode (opens in a new tab) | |||
| 3 | Consecutive Numbers | LeetCode | Medium | Solve Consecutive Numbers on LeetCode (opens in a new tab) | |||
| 4 | Last Person to Fit in the Bus | LeetCode | Medium | Solve Last Person to Fit in the Bus on LeetCode (opens in a new tab) | |||
| 5 | Restaurant Growth | LeetCode | Medium | Solve Restaurant Growth on LeetCode (opens in a new tab) | |||
| 6 | Department Top Three Salaries | LeetCode | Hard | Solve Department Top Three Salaries on LeetCode (opens in a new tab) |