Full answer
sql
CREATE TABLE scores (player_id INTEGER PRIMARY KEY, score INTEGER NOT NULL);
CREATE INDEX scores_score ON scores(score DESC, player_id);
INSERT INTO scores VALUES (1, 900), (2, 750), (3, 750), (4, 500), (5, 990);
SELECT player_id, score, (SELECT COUNT(*) FROM scores s2 WHERE s2.score > s.score) + 1 AS rank
FROM scores s ORDER BY score DESC, player_id;| player_id | score | rank |
|---|---|---|
| 5 | 990 | 1 |
| 1 | 900 | 2 |
| 2 | 750 | 3 |
| 3 | 750 | 3 |
| 4 | 500 | 5 |
The rank is "how many players score more, plus one", which ties naturally share. With an index on score, the count reads index entries above the player's score.
Scaling notes:
- Top 100: index read, always fast.
- A player near the top: small count, fast.
- A player near the bottom of 10 million: the count touches millions of index entries, which can be slow under load.
Common answers: compute ranks periodically into a table (rank as of five minutes ago is often acceptable), use score buckets with counts per bucket to estimate rank quickly, or keep the live board in an in-memory sorted structure and treat the database as the record of truth.
Ties need a rule: equal rank, or earlier achievement wins (add achieved_at to the ordering).
sql
CREATE TABLE scores (player_id INTEGER PRIMARY KEY, score INTEGER NOT NULL);
CREATE INDEX scores_score ON scores(score DESC, player_id);
INSERT INTO scores VALUES (1, 900), (2, 750), (3, 750), (4, 500), (5, 990);
SELECT player_id, score, (SELECT COUNT(*) FROM scores s2 WHERE s2.score > s.score) + 1 AS rank
FROM scores s ORDER BY score DESC, player_id;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- Index scores for top-N reads
- Rank = count of higher scores + 1
- Exact ranks for low positions get expensive
- Periodic snapshots or buckets scale better
- Define the tie rule
Common mistakes
- Running a full window rank on every request
- Ignoring ties
Follow-ups
- How would you show the players ranked just above and below a given player?
- How would you shard a global leaderboard?
Tips
- Separate top-N reads from single-player rank