Redis ZRANGEBYSCORE – How to get elements of sorted set by score range and in asc order

1 month ago Lalit Bhagtani 0

In this tutorial, we will learn about how to get all the elements of the sorted set value having a score between a specific range and in ascending order by score. For this, we will use redis ZRANGEBYSCORE command.


This command returns all the elements of the sorted set value, whose score is greater than equal to min ( inclusive ) score and less than equal to max ( inclusive ) score passed as an argument. Here elements are returned in ascending order by score and for elements having equal score, they are arranged in ascending lexicographical order.

By default min and max arguments are closed interval (inclusive) but it is possible to specify them as open interval (exclusive) by prefixing them with ( character. For example :- 


Will return all elements with 1 < score <= 5 while:


Will return all the elements with 5 < score < 10 (5 and 10 excluded).

min and max argument can be -inf (negative infinity) and +inf (positive infinity), so that you are not required to know the highest or lowest score in the sorted set to get all elements from or up to a certain score range.

Optional Arguments

The Redis ZRANGEBYSCORE command takes following optional arguments :-

  1. WITHSCORES :- It returns score of the element together with the element. In this case, returned array will contain value1, score1, …. valueN, scoreN instead of value1, …., valueN.
  2. LIMIT :- It returns the count matching elements starting from the offset. If count value is negative then all elements are returned from the offset.

An empty set is returned, if key does not exist and error is returned, if key exist but value stored at the key is not of sorted set datatype. The syntax of redis ZRANGEBYSCORE command is as follows :- 

Syntax :-

redis host:post> ZRANGEBYSCORE <keyname> <min> <max> [WITHSCORES] [LIMIT offset count]

Output :-

- (array) reply, representing elements of the sorted set in the specified range.
- Empty Set, if key does not exists.
- Error, if key exist and value stored at the key is not a sorted set.

Example :-


References :-

  1. ZRANGEBYSCORE Command Docs

That’s all for how to get all the elements of the sorted set value having score between specific range and in ascending order by score, stored in redis datastore. If you liked it, please share your thoughts in comments section and share it with others too.