Skip to content
We areTOP 1%

What is the difference between ROW_NUMBER, RANK and DENSE_RANK?

EasyConceptSQL: Window Functions
Track your progress
First attempt
Re-solve after a few days
Final pass before interviews

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_NUMBER gives every row a different number and breaks ties arbitrarily, unless you add a tie-breaking column.
  • RANK gives tied rows the same rank and then skips numbers, leaving gaps (1, 2, 2, 4).
  • DENSE_RANK gives tied rows the same rank without gaps (1, 2, 2, 3).
  • Use ROW_NUMBER to pick exactly one row per group, such as each customer's latest order, and DENSE_RANK for 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

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account