skip to content

row_number, rank and dense_rank

three ways to number rows. they only disagree on ties, which is exactly when it matters.

address
everything.analytics.ranking
part
part 4, windows, grouping and recursion
chapter
chapter 5 of 11
reading time
7 min

three ways to number rows in order. row_number gives every row its own number. rank gives tied rows the same number and then skips ahead. dense_rank gives tied rows the same number and doesn't skip.

they agree on every row without a tie. ties are the only place they differ, which is exactly where the questions are.

the picture

you know how a race can have two people share second place, and then the next runner is... third? or fourth? depends who you ask. SQL has one function per answer, and picking the wrong one quietly changes who's on the podium.

the class of 37 graded students, ranked by grade point average. three are on 4.00, two on 3.50, nine on 3.00:

number =
gpa 4.003 tied
1Elena Petrov2Ananya Rao3Nora Jensen
gpa 3.502 tied
4Mateo Garcia5Mateus Lima
gpa 3.25
6Lucas Costa
gpa 3.009 tied
7Omar Haddad8Robert'); DROP TABLE students;--9Fatima Zahra10Alex Kim11Hugo Martin12Felix Wagner13Tariq Aziz14Alex Kim15Sana Malik

1 to 15, no repeats. the three students on 4.00 are numbered 1, 2, 3 by id, because the window says ORDER BY gpa DESC, id. take the id away and the order among them is up to the sort.

real output, postgres 18.6 (PGlite 0.5.12) · ranking
pick a function. each line is one gpa, the people on it are tied. rank skips the numbers a tie used up (dashed: nobody got them). dense_rank never skips. row_number never ties, so somebody has to decide who goes first.

think of it as three questions. row_number: "what line are you on?" rank: "how many people beat you, plus one?" dense_rank: "how many different scores beat you, plus one?"

the three of them

the gpa is a view, so the rest of the page can say FROM gpa:

sqldb=school · session gpa
CREATE VIEW gpa AS
SELECT s.id, s.name,
       round(avg(CASE e.grade WHEN 'A' THEN 4 WHEN 'B' THEN 3 WHEN 'C' THEN 2
                              WHEN 'D' THEN 1 ELSE 0 END), 2) AS gpa
FROM students AS s
JOIN enrollments AS e ON e.student_id = s.id
WHERE e.grade IS NOT NULL
GROUP BY s.id;
 
SELECT id, name, gpa,
       row_number() OVER (ORDER BY gpa DESC, id) AS row_number,
       rank()       OVER (ORDER BY gpa DESC)     AS rank,
       dense_rank() OVER (ORDER BY gpa DESC)     AS dense_rank
FROM gpa
ORDER BY gpa DESC, id
LIMIT 8;
output, from postgres 18.6
#1 · CREATE VIEW
#2 · SELECT 8
idint4nametextgpanumericrow_numberint8rankint8dense_rankint8
20Elena Petrov4.00111
28Ananya Rao4.00211
30Nora Jensen4.00311
27Mateo Garcia3.50442
38Mateus Lima3.50542
8Lucas Costa3.25663
10Omar Haddad3.00774
13Robert'); DROP TABLE students;--3.00874
(8 rows)

all three need an ORDER BY inside OVER, since "first" means nothing without one, and they ignore the frame: they number the whole partition. and notice the outer ORDER BY is gpa DESC, id, not gpa DESC. the result has ties too, and a page that prints rows in an order nobody promised teaches the bug. (ORDER BY has that rule.)

predict the output
sql
-- three students tie for first.
-- what does dense_rank() give the next student?
SELECT name, gpa, dense_rank() OVER (ORDER BY gpa DESC)
FROM gpa;

who's in the top four?

the classic use: number the rows in a subquery, keep the small numbers outside (a window can't go in WHERE, window functions has why). same question, same data, three answers:

n is =
query.sql
  1. 1SELECT id, name, gpa, n
  2. 2FROM (SELECT *, row_number() OVER (ORDER BY gpa DESC, id) AS n FROM gpa) AS t
  3. 3WHERE n <= 4
  4. 4ORDER BY n, id;
the result for row_number
idint4nametextgpanumericnint8
20Elena Petrov4.001
28Ananya Rao4.002
30Nora Jensen4.003
27Mateo Garcia3.504
(4 rows)

row_number: exactly four rows, because every number is used once. Mateo Garcia gets fourth place and Mateus Lima, on the same gpa, doesn't, only because 27 < 38.

real output, postgres 18.6 (PGlite 0.5.12) · ranking
switch the function. row_number keeps exactly four rows and leaves Mateus Lima out, though he has the same gpa as Mateo Garcia. rank keeps both: five rows. dense_rank reads "top four" as "top four gpas": fifteen rows.

none of them is wrong. they're answers to different questions, and the question usually comes from somebody else:

  • "exactly four rows, for a page of four cards": row_number, with a tiebreaker you can defend.
  • "everyone who placed fourth or better": rank. it's what a leaderboard means, and it's what FETCH FIRST 4 ROWS WITH TIES gives you without a window at all (LIMIT and OFFSET).
  • "the four best scores, and everyone on them": dense_rank.

row_number and ties

row_number has to give tied rows different numbers, so something has to decide their order. if your ORDER BY doesn't, postgres's sort does, and the sort makes no promise about rows that compare equal.

here it is without the id, on purpose, fed the same rows in two different orders. the outer ORDER BY is total, so the rows print in a fixed order; watch the number each one gets:

rows arrive =
query.sql
  1. 1SELECT id, name, gpa, row_number() OVER (ORDER BY gpa DESC) AS n
  2. 2FROM gpa
  3. 3ORDER BY gpa DESC, id
  4. 4LIMIT 6;
the result for as stored
idint4nametextgpanumericnint8
20Elena Petrov4.001
28Ananya Rao4.002
30Nora Jensen4.003
27Mateo Garcia3.505
38Mateus Lima3.504
8Lucas Costa3.256
(6 rows)

row_number() OVER (ORDER BY gpa DESC), no tiebreaker, rows read from the view: Mateus Lima (38) comes out 4th, ahead of Mateo Garcia (27).

real output, postgres 18.6 (PGlite 0.5.12) · ranking
switch how the rows reach the window. same OVER (ORDER BY gpa DESC), same data. as stored, Mateus Lima is 4th and Mateo Garcia 5th. in reverse, Nora Jensen jumps from 3rd to 1st. add id to the window and both inputs agree.

the first one, to run yourself:

sqldb=school · session gpa
continues session gpa (1 earlier block run first)
SELECT id, name, gpa,
       row_number() OVER (ORDER BY gpa DESC) AS n
FROM gpa
ORDER BY gpa DESC, id
LIMIT 6;
output, from postgres 18.6
SELECT 6
idint4nametextgpanumericnint8
20Elena Petrov4.001
28Ananya Rao4.002
30Nora Jensen4.003
27Mateo Garcia3.505
38Mateus Lima3.504
8Lucas Costa3.256
(6 rows)

fed in reverse, Nora Jensen moved from 3rd to 1st. same window, same data, different numbers: both answers are correct, because the query never said who goes first among equals. a different plan, a different postgres version, or an UPDATE that moved rows around can change it again. so the rule is short: make the window's ORDER BY total whenever row_number feeds anything that matters. ORDER BY gpa DESC, id costs nothing and settles it.

the relatives

three more ranking functions answer "where do I stand?" as a fraction or a bucket:

sqldb=school · session gpa
continues session gpa (2 earlier blocks run first)
SELECT name, gpa,
       round((percent_rank() OVER w)::numeric, 3) AS percent_rank,
       round((cume_dist() OVER w)::numeric, 3)    AS cume_dist,
       ntile(4) OVER (ORDER BY gpa DESC, id) AS quartile
FROM gpa
WINDOW w AS (ORDER BY gpa DESC)
ORDER BY gpa DESC, id
LIMIT 8;
output, from postgres 18.6
SELECT 8
nametextgpanumericpercent_ranknumericcume_distnumericquartileint4
Elena Petrov4.000.0000.0811
Ananya Rao4.000.0000.0811
Nora Jensen4.000.0000.0811
Mateo Garcia3.500.0830.1351
Mateus Lima3.500.0830.1351
Lucas Costa3.250.1390.1621
Omar Haddad3.000.1670.4051
Robert'); DROP TABLE students;--3.000.1670.4051
(8 rows)
  • percent_rank() is (rank − 1) / (rows − 1): 0 for the top, 1 for the bottom. the 3.50s get 3/36 = 0.083.
  • cume_dist() is the share of rows at or ahead of you, ties included. the 3.50s get 5/37 = 0.135.
  • ntile(4) deals the rows into 4 buckets as evenly as it can, like dealing cards. it splits ties without blinking (hence the id again), so it's a bucket number, not a rank.

and if you want the rank a value would have without adding it to the table, that's a hypothetical-set aggregate: rank(3.6) WITHIN GROUP (ORDER BY gpa DESC), in percentiles and medians.

keylines

  • row_number never ties. rank ties and skips. dense_rank ties and doesn't skip.
  • they disagree only on ties, so "top n" with each gives a different number of rows.
  • row_number over a non-unique ORDER BY is a coin toss. end the ORDER BY with a key.
  • rank ≤ n is the same set as FETCH FIRST n ROWS WITH TIES.
  • percent_rank, cume_dist and ntile place a row as a fraction or a bucket.