## How to get rank of an element of sorted set – Redis ZRANK | ZREVRANK

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

In this tutorial, we will learn about how to get the rank of an element of the sorted set value stored at a key in redis datastore, by using redis ZRANK and ZREVRANK commands.

## ZRANK Command

This command is used to return the rank of the element of sorted set value stored at the specified key. The elements in the sorted set are in ascending order by score and ascending lexicographical order is used for the elements with equal score. The rank is zero based, which means that the member with the lowest score has rank 0.

Nil is returned, when element does not exist in the sorted set or key does not exist. Error is returned, when key exist but value stored at the key is not of sorted set datatype.

The syntax of redis ZRANK command is as follows :-

## Syntax :-

`redis host:post> ZRANK <keyname> <element>`

## Output :-

```- (integer) reply, representing rank of the element stored in the sorted set.
- (nil), if element does not exist in the sorted set or if key does not exist.
- Error, if key exist and value stored at the key is not a sorted set.
```

## ZREVRANK Command :-

This command is used to return the rank of the element of sorted set value stored at the specified key. The elements in the sorted set are in descending order by score. Descending lexicographical order is used for the elements with equal score. The rank is zero based, which means that the member with the highest score has rank 0.

Nil is returned, when element does not exist in the sorted set or key does not exist. Error is returned, when key exist but value stored at the key is not of sorted set datatype.

The syntax of redis ZREVRANK command is as follows :-

## Syntax :-

`redis host:post> ZREVRANK <keyname> <element>`

## Output :-

```- (integer) reply, representing rank of the element stored in the sorted set.
- (nil), if element does not exist in the sorted set or if key does not exist.
- Error, if key exist and value stored at the key is not a sorted set.
```

## References :-

That’s all for how to get the rank of an element of the sorted set value stored in redis datastore. If you liked it, please share your thoughts in comments section and share it with others too.