How to Use ZRANGEBYSCORE in Redis: Syntax and Examples
Use the
ZRANGEBYSCORE command in Redis to get all elements in a sorted set with scores within a specified range. The syntax is ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT offset count], where min and max define the score range to filter the elements.Syntax
The ZRANGEBYSCORE command retrieves members in a sorted set with scores between min and max. Optional flags include WITHSCORES to return scores alongside members, and LIMIT offset count to paginate results.
- key: The name of the sorted set.
- min: Minimum score (inclusive by default).
- max: Maximum score (inclusive by default).
- WITHSCORES: Optional, returns scores with members.
- LIMIT offset count: Optional, limits the number of results starting from
offset.
redis
ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT offset count]
Example
This example shows how to add members with scores to a sorted set and then retrieve members with scores between 50 and 100, including their scores.
redis
127.0.0.1:6379> ZADD players 30 "Alice" 60 "Bob" 90 "Charlie" 120 "Diana" (integer) 4 127.0.0.1:6379> ZRANGEBYSCORE players 50 100 WITHSCORES 1) "Bob" 2) "60" 3) "Charlie" 4) "90"
Output
1) "Bob"
2) "60"
3) "Charlie"
4) "90"
Common Pitfalls
Common mistakes include:
- Using exclusive ranges without proper syntax. To exclude a boundary, prefix the score with
(, e.g.,(50excludes 50. - Forgetting that scores are strings representing floating-point numbers, so use correct numeric values.
- Not using
WITHSCORESwhen you need the scores returned. - Misusing
LIMITwithout understanding offset and count.
redis
Wrong: ZRANGEBYSCORE players 50 100 Right: ZRANGEBYSCORE players (50 100 WITHSCORES LIMIT 0 2)
Quick Reference
| Option | Description |
|---|---|
| key | Name of the sorted set |
| min | Minimum score (inclusive or exclusive with '(') |
| max | Maximum score (inclusive or exclusive with '(') |
| WITHSCORES | Return members with their scores |
| LIMIT offset count | Return a subset of results starting at offset |
Key Takeaways
ZRANGEBYSCORE fetches sorted set members within a score range efficiently.
Use parentheses '(' before min or max to exclude that boundary from results.
Add WITHSCORES to get scores along with members in the output.
LIMIT helps paginate results by specifying offset and count.
Scores are numeric strings; use correct numeric values for filtering.