Databases & SQL Master Course — 082. ROW_NUMBER RANK and DENSE_RANK
Lesson 082 ROW_NUMBER RANK and DENSE_RANK
Prerequisites and objectives
You understand OVER and partitions. You will compare ROW_NUMBER, RANK, and DENSE_RANK, choose a tie policy from a business question, and distinguish deterministic row selection from shared score rank. The fixture is a fictional points contest with deliberate ties.
Create the practice fixture
Use a fresh SQLite database supporting window functions. North has two entries tied at ninety points and one at seventy. South has eighty and sixty. entry_id is a unique stable tie-breaker for selecting individual rows; it is not part of the business score itself.
CREATE TABLE scores (entry_id INTEGER PRIMARY KEY,team TEXT NOT NULL,name TEXT NOT NULL,points INTEGER NOT NULL);
INSERT INTO scores VALUES (1,'North','Ari',90),(2,'North','Bea',90),(3,'North','Cleo',70),(4,'South','Dara',80),(5,'South','Eli',60);
Separate three ranking questions
ROW_NUMBER assigns consecutive positions to individual rows within a partition. RANK assigns the same rank to peers and leaves gaps after ties. DENSE_RANK also shares ranks among peers but advances to the next distinct rank without gaps. Each function answers a different question about ordering.
For North, a deterministic row order gives positions one, two, three. Ranking by points alone gives competition ranks one, one, three and dense ranks one, one, two. Neither is a bug. The correct choice depends on whether the requirement concerns a fixed number of entries, competition placement, or distinct score levels.
SELECT entry_id,ROW_NUMBER() OVER (PARTITION BY team ORDER BY points DESC,entry_id) AS position,RANK() OVER (PARTITION BY team ORDER BY points DESC) AS competition_rank,DENSE_RANK() OVER (PARTITION BY team ORDER BY points DESC) AS score_level FROM scores ORDER BY entry_id;
| Entry | Row number | Rank | Dense rank |
|---|---|---|---|
| 1 | 1 | 1 | 1 |
| 2 | 2 | 1 | 1 |
| 3 | 3 | 3 | 2 |
| 4 | 1 | 1 | 1 |
| 5 | 2 | 2 | 2 |

Choose tie-breakers without changing the question
The ROW_NUMBER window orders by points descending and then entry_id. That makes Ari precede Bea reproducibly in this fixture. Without a complete tie-breaker, equal-point rows can receive either relative position. If a business process selects exactly one tied row, it needs a stated selection policy.
The RANK and DENSE_RANK windows intentionally omit entry_id. Including a unique identifier would make every ordering tuple distinct and remove the shared point ranks. A deterministic display order can still use entry_id outside the ranking window without redefining which scores are tied.
Interpret gaps and score levels
RANK can be understood as one plus the number of rows with a better ordering value. Two entries occupy the top level, so the next entry ranks third. DENSE_RANK counts better distinct ordering levels instead, so the next score is level two. This difference matters when a report asks for the top two score levels rather than the top two entries.
ROW_NUMBER always distinguishes rows even when their scores tie. It is therefore useful for pagination or selecting a bounded number of records, provided the order is deterministic. It should not be presented as a fair competition rank unless that is actually the intended rule.
Keep partitions and missing-value policy explicit
PARTITION BY team restarts all three calculations for each team. Removing it creates a single contest across both teams. Scores are required here, avoiding ambiguity about how missing scores should participate. A real ranking system should decide whether missing entries are excluded, ranked separately, or displayed without a rank.
Rank numbers are query results, not persistent identities. Adding a better entry can change existing ranks without changing any entry identifier. Do not use a computed rank as a foreign key or as a permanent reference to the person or event being ranked.
Four worked exercises
Exercise 1
Rank all entries globally rather than separately by team.
Worked solution
SELECT entry_id,RANK() OVER (ORDER BY points DESC) FROM scores ORDER BY entry_id;
The two ninety-point entries share first place, eighty ranks third, seventy fourth, and sixty fifth. Removing PARTITION BY changes the comparison population, not merely the displayed label.
Exercise 2
Show how adding entry_id to RANK changes the definition of a tie.
Worked solution
SELECT entry_id,RANK() OVER (PARTITION BY team ORDER BY points DESC,entry_id) FROM scores ORDER BY entry_id;
The unique identifier makes every ordering tuple distinct, so the North scores no longer share rank one. Use this only if the business ordering truly includes the identifier, not as an accidental way to stabilize a score-based rank.
Exercise 3
Select North entries from its first two distinct score levels.
Worked solution
WITH ranked AS (SELECT entry_id,team,DENSE_RANK() OVER (PARTITION BY team ORDER BY points DESC) AS level FROM scores) SELECT entry_id FROM ranked WHERE team='North' AND level<=2 ORDER BY entry_id;
All three North entries qualify because ninety and seventy are the first two distinct levels. A top-two-levels request can return more than two rows. The outer query filters after ranking.
Exercise 4
Select exactly the first two North entries under the declared stable order.
Worked solution
WITH ranked AS (SELECT entry_id,team,ROW_NUMBER() OVER (PARTITION BY team ORDER BY points DESC,entry_id) AS position FROM scores) SELECT entry_id FROM ranked WHERE team='North' AND position<=2 ORDER BY entry_id;
The result contains Ari and Bea. ROW_NUMBER enforces a row-count limit for this partition, while the tie-breaker makes the choice reproducible. This is a different contract from selecting two distinct score levels.
Knowledge check
Question 1
Which North rank sequence has gaps after the tie?
- 1, 2, 3 from DENSE_RANK
- 1, 1, 2 from ROW_NUMBER
- 1, 1, 3 from RANK
- 1, 2, 2 from RANK
Answer and explanation
C. Two rows occupy the first score level, so competition rank advances to three.
Question 2
Which function fits exactly two selected rows per sufficiently large group?
- DENSE_RANK by score alone
- ROW_NUMBER with a complete order
- RANK by score alone
- COUNT without OVER
Answer and explanation
B. Individual row positions support an exact bound, with tie policy made explicit.
Question 3
Why omit entry_id from score-based RANK?
- A unique identifier is ignored when forming peers
- Including an identifier would split every partition
- PARTITION BY already breaks ties between equal scores
- A unique tie-breaker would eliminate equal-score peers
Answer and explanation
D. Peer equality uses the complete window ordering tuple.
Question 4
What does DENSE_RANK count here?
- Only rows with unique names
- Distinct score levels without gaps
- Physical storage positions
- The number of teams in the table
Answer and explanation
B. Equal scores share a level and the next distinct score advances by one.
Question 5
Why is rank unsuitable as permanent identity?
- It can change when the comparison population changes
- Ranking never assigns the same value twice
- Its value is determined only by the row’s primary key
- It is calculated before the comparison population is filtered
Answer and explanation
A. Ranking describes a relative result, while identity should remain stable.
Pitfalls and summary
Do not choose a ranking function before defining the tie and selection policy. Separate individual positions, competition ranks, and distinct score levels. Keep deterministic tie-breakers where needed without accidentally changing score peers, and label the comparison partition so readers know what each rank means.
SQLite behavior and references
Examples were checked with SQLite 3.53.1 on 10 October 2026. Use a SQLite SQL editor; Python is not a prerequisite. Verify dialect-specific functions, comparison rules, and numeric behavior before moving the examples to another engine.
Primary references
- SQLite window functions: Partitions, ordering, frames, and built-in functions
- SQLite SELECT: Query stages and final ordering