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:
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.
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:
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;| idint4 | nametext | gpanumeric | row_numberint8 | rankint8 | dense_rankint8 |
|---|---|---|---|---|---|
| 20 | Elena Petrov | 4.00 | 1 | 1 | 1 |
| 28 | Ananya Rao | 4.00 | 2 | 1 | 1 |
| 30 | Nora Jensen | 4.00 | 3 | 1 | 1 |
| 27 | Mateo Garcia | 3.50 | 4 | 4 | 2 |
| 38 | Mateus Lima | 3.50 | 5 | 4 | 2 |
| 8 | Lucas Costa | 3.25 | 6 | 6 | 3 |
| 10 | Omar Haddad | 3.00 | 7 | 7 | 4 |
| 13 | Robert'); DROP TABLE students;-- | 3.00 | 8 | 7 | 4 |
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.)
-- 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:
- 1SELECT id, name, gpa, n
- 2FROM (SELECT *, row_number() OVER (ORDER BY gpa DESC, id) AS n FROM gpa) AS t
- 3WHERE n <= 4
- 4ORDER BY n, id;
| idint4 | nametext | gpanumeric | nint8 |
|---|---|---|---|
| 20 | Elena Petrov | 4.00 | 1 |
| 28 | Ananya Rao | 4.00 | 2 |
| 30 | Nora Jensen | 4.00 | 3 |
| 27 | Mateo Garcia | 3.50 | 4 |
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.
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 TIESgives 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:
- 1SELECT id, name, gpa, row_number() OVER (ORDER BY gpa DESC) AS n
- 2FROM gpa
- 3ORDER BY gpa DESC, id
- 4LIMIT 6;
| idint4 | nametext | gpanumeric | nint8 |
|---|---|---|---|
| 20 | Elena Petrov | 4.00 | 1 |
| 28 | Ananya Rao | 4.00 | 2 |
| 30 | Nora Jensen | 4.00 | 3 |
| 27 | Mateo Garcia | 3.50 | 5 |
| 38 | Mateus Lima | 3.50 | 4 |
| 8 | Lucas Costa | 3.25 | 6 |
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).
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:
SELECT id, name, gpa,
row_number() OVER (ORDER BY gpa DESC) AS n
FROM gpa
ORDER BY gpa DESC, id
LIMIT 6;| idint4 | nametext | gpanumeric | nint8 |
|---|---|---|---|
| 20 | Elena Petrov | 4.00 | 1 |
| 28 | Ananya Rao | 4.00 | 2 |
| 30 | Nora Jensen | 4.00 | 3 |
| 27 | Mateo Garcia | 3.50 | 5 |
| 38 | Mateus Lima | 3.50 | 4 |
| 8 | Lucas Costa | 3.25 | 6 |
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:
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;| nametext | gpanumeric | percent_ranknumeric | cume_distnumeric | quartileint4 |
|---|---|---|---|---|
| Elena Petrov | 4.00 | 0.000 | 0.081 | 1 |
| Ananya Rao | 4.00 | 0.000 | 0.081 | 1 |
| Nora Jensen | 4.00 | 0.000 | 0.081 | 1 |
| Mateo Garcia | 3.50 | 0.083 | 0.135 | 1 |
| Mateus Lima | 3.50 | 0.083 | 0.135 | 1 |
| Lucas Costa | 3.25 | 0.139 | 0.162 | 1 |
| Omar Haddad | 3.00 | 0.167 | 0.405 | 1 |
| Robert'); DROP TABLE students;-- | 3.00 | 0.167 | 0.405 | 1 |
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 theidagain), 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.