## Redis ZREVRANGE – How to get elements of sorted set by Desc Rank Range

###### 2 months ago Lalit Bhagtani 0

In this tutorial, we will learn about how to get one or more elements of the sorted set value having rank between specific range and in descending order by score. For this, we will use Redis ZREVRANGE commands.

## ZREVRANGE Command

The ZREVRANGE command, returns one or more elements of the sorted set value stored at specified key, defined by the specified range. The elements in the sorted set are in descending order by score. Descending lexicographical order is used for the elements with equal score.

Range is defined by the start ( inclusive ) and end ( inclusive ) offsets, these offsets are zero based indexes where 0 means the first element, 1 means the second element and so on. Negative numbers can also be used to provide an offset starting from the end of the list value, here -1 means the last element, -2 means second last element and so on.

An out of range offsets are handle in the following ways :-

1. ( start > end ) or ( start > size of sorted set ) :- Result is an empty list.
2. ( end > size of sorted set ) :- Index of last element of the sorted set value is set to end 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 WITHSCORES ( optional ) argument can be passed in the command, to get the scores of the elements together with the elements. In this case, returned array will contain value1, score1, …. valueN, scoreN instead of value1, …., valueN.

The syntax of redis ZREVRANGE command is as follows :-

## Syntax :-

`redis host:post> ZREVRANGE <keyname> <start> <stop> [ WITHSCORES ]`

## 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.
```

## References :-

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