Skip to the workspace
Pebellslearn by building
Sorted Sets  ›  Lesson

ZRANGEBYSCORE and ZCOUNT

ZRANGEBYSCORE 12 minZRANGEBYSCORE returns the members whose scores fall between a minimum and a maximum, and ZCOUNT only counts them; both bounds are inclusive unless prefixed with a bracket.

redis / ZRANGEBYSCORE and ZCOUNT

Explore each scene at your own pace.

01 · The rule

The rule

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) 1
  • ZRANGEBYSCORE key min max returns members whose score lies between min and max, lowest score first.
  • ZCOUNT key min max takes 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 min or max is included.
  • Put ( in front of a bound to make it exclusive: (100 means "more than 100", and as a max, "less than 100".
  • -inf and +inf mean "no lower limit" and "no upper limit".
  • LIMIT offset count pages through a big band: LIMIT 0 10 gives 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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.