← Back to SQL, page 17

sql-0321 · Hard senior

Design storage for a game leaderboard that shows a player's rank among millions of players.

Store scores in a table indexed on (score DESC, player_id). Top-N pages are cheap index reads. A single player's rank is COUNT(*) of players with a higher score, which an index range count answers but still touches many entries at the top of large boards. At very large scale, keep ranks in a cache such as a sorted set, or precompute rank buckets periodically.

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_idscorerank
59901
19002
27503
37503
45005

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