Before continuing: This entry is part of the window functions guide. If you are new to the topic, start with OVER.
Examples
| id | total |
|---|---|
| 108 | 249.0 |
| 111 | 249.0 |
| 114 | 203.9 |
| 104 | 179.0 |
| 118 | 179.0 |
SELECT id,
total,
RANK() OVER (ORDER BY total DESC) AS rank_position,
DENSE_RANK() OVER (ORDER BY total DESC) AS dense_position
FROM orders
WHERE id IN (104, 108, 111, 114, 118)
ORDER BY total DESC, id;| id | total | rank_position | dense_position |
|---|---|---|---|
| 108 | 249.0 | 1 | 1 |
| 111 | 249.0 | 1 | 1 |
| 114 | 203.9 | 3 | 2 |
| 104 | 179.0 | 4 | 3 |
| 118 | 179.0 | 4 | 3 |
When to choose each one
For a meaningful ranking, define an ORDER BY within OVER. SQL Server requires it syntactically; PostgreSQL and SQLite let you leave it out, but then there is no defined order for a useful ranking. In SQLite, without ORDER BY, every row counts as a peer and both RANK and DENSE_RANK return 1. If you do not want to break ties, do not add a unique column such as id to the window's ordering.
Differences and trade-offs
Which question each one answers
Use RANK when the position should reflect how many rows come before. In a competition, two people tied for first place can be followed by third place.
Use DENSE_RANK when you want to number levels or groups of distinct values. After two rows on level 1, the next distinct value goes on level 2.
Neither option is better in every case: the choice depends on what the ranking means.
How it differs from ROW_NUMBER
ROW_NUMBER gives every row a different number, even when the values are tied. To get a stable order with ROW_NUMBER you usually add a tiebreaker. With RANK and DENSE_RANK, that tiebreaker would change which rows count as tied.
Common mix-ups with RANK and DENSE_RANK
Removing ties by accident
RANK() OVER (ORDER BY total DESC, id)Because the id is different on every row, no two rows are equal under the full ordering any more. The function will give them different positions. Use the id only in the outer ORDER BY if you want a stable presentation without breaking the tie.