ZRANGEBYSCORE and ZCOUNT
Wordcraft splits players into leagues: bronze below 100 points, silver from 100 up to 400, gold at 400 and above. A league page needs "everyone with a score in this band", and the lobby just needs "how many". That is a question about scores, not positions.
The rule
Bounds are scores, inclusive by default; a bracket makes one exclusive.
The leaderboard holds tom 90, ravi 150, asha 320 and meera 410.
127.0.0.1:6379> ZRANGEBYSCORE leaderboard 100 400
1) "ravi"
2) "asha"
127.0.0.1:6379> ZCOUNT leaderboard 100 400
(integer) 2
127.0.0.1:6379> ZRANGEBYSCORE leaderboard 400 +inf WITHSCORES
1) "meera"
2) "410"
127.0.0.1:6379> ZCOUNT leaderboard -inf (100
(integer) 1ZRANGEBYSCORE key min maxreturns members whose score lies betweenminandmax, lowest score first.ZCOUNT key min maxtakes the same bounds but only replies with how many, which is cheaper when you do not need the names.- Both bounds are inclusive: a score exactly equal to
minormaxis included. - Put
(in front of a bound to make it exclusive:(100means "more than 100", and as a max, "less than 100". -infand+infmean "no lower limit" and "no upper limit".LIMIT offset countpages through a big band:LIMIT 0 10gives the first ten.
Since Redis 6.2, the same query can be written with the unified ZRANGE: ZRANGE leaderboard 100 400 BYSCORE. ZRANGEBYSCORE still works and you will meet it in plenty of existing code.
Positions (ZRANGE) and scores (ZRANGEBYSCORE) are easy to mix up: ZRANGE leaderboard 0 2 means "the first three members", while ZRANGEBYSCORE leaderboard 0 2 means "members scoring between 0 and 2", which here is nobody.
The shortcut
Draw the number line. Mark each member at its score, draw the band, use a filled dot for an inclusive end and an open dot for a ( end, then read the names inside from left to right.
Place the members
90 tom, 150 ravi, 320 asha, 410 meera.
Drills
Answer fast — trust the rule.
What does ZCOUNT leaderboard 150 320 reply for tom 90, ravi 150, asha 320, meera 410?
Same set. What does ZCOUNT leaderboard (150 320 reply?
Which command lists everyone below 100 points?
What does ZRANGEBYSCORE leaderboard 0 2 return for this leaderboard?
Remember
- Bounds are scores, inclusive by default; a bracket makes one exclusive.
- Draw the number line, mark the band's ends, read the names inside.
- ZCOUNT counts the band; ZRANGE ... BYSCORE is the modern spelling of ZRANGEBYSCORE.
