ROW_NUMBER()
VS
RANK()
VS
DENSE_RANK()
ROW_NUMBER()
Purpose: Assigns a unique sequential number
to each row, starting from 1, without any
gaps, even if there are ties
During ties: When there are multiple rows
with the same value, ROW_NUMBER() will still
assign them unique sequential numbers.
SELECT
Name
, Score
, ROW_NUMBER() OVER (ORDER BY Score DESC) AS RN
FROM
Students;
RANK()
Purpose: Assigns a rank to each row, starting
from 1. It handles ties by giving the same rank to
rows with identical values but leaves gaps in the
ranking sequence.
During ties: If there are ties, rows with the same
value will receive the same rank, and the next
rank will skip the number(s) of the tied ranks.
SELECT
Name
, Score
, RANK() OVER (ORDER BY Score DESC) AS RN
FROM
Students;
DENSE_RANK()
Purpose: Similar to RANK(), but does not leave
gaps in the ranking sequence when there are
ties.
During ties: If there are ties, all rows with the
same value will receive the same rank, and the
next rank will be consecutive (i.e., no gaps).
SELECT
Name
, Score
, DENSE_RANK() OVER (ORDER BY Score DESC) AS RN
FROM
Students;