Redis Sorted Set: Remove by Score (Detailed Guide w/ Code Examples)

Use Case(s)

Removing elements from a Redis Sorted Set based on their scores is useful when managing time-sensitive data, such as expiring cache entries, removing outdated records, or trimming leaderboards.

Code Examples


import redis client = redis.StrictRedis(host='localhost', port=6379, db=0) # Add some elements with scores client.zadd('myset', {'member1': 10, 'member2': 20, 'member3': 30}) # Remove all elements with scores between 15 and 25 (inclusive) client.zremrangebyscore('myset', 15, 25)


const redis = require('redis'); const client = redis.createClient(); client.zadd('myset', 10, 'member1'); client.zadd('myset', 20, 'member2'); client.zadd('myset', 30, 'member3'); client.zremrangebyscore('myset', 15, 25, (err, response) => { if (err) throw err; console.log(response); // Number of members removed });


package main import ( "fmt" "" "context" ) func main() { ctx := context.Background() client := redis.NewClient(&redis.Options{ Addr: "localhost:6379", }) client.ZAdd(ctx, "myset", &redis.Z{Score: 10, Member: "member1"}) client.ZAdd(ctx, "myset", &redis.Z{Score: 20, Member: "member2"}) client.ZAdd(ctx, "myset", &redis.Z{Score: 30, Member: "member3"}) client.ZRemRangeByScore(ctx, "myset", "15", "25") }

Best Practices

  • Always handle possible errors when working with Redis operations.
  • Make use of transactions (MULTI/EXEC) if multiple operations depend on each other to maintain atomicity.

Common Mistakes

  • Not converting score ranges to string when required in certain languages or libraries (e.g., Go).
  • Forgetting to check the number of removed elements to ensure the operation's success.


Q: What happens if there are no elements within the specified score range? A: The command will simply return 0, indicating no elements were removed.

Q: Can score ranges be inclusive/exclusive? A: Yes, you can specify inclusive ranges using [min,max] and exclusive ranges using (min,max).

Was this content helpful?

Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.