0
0
RedisHow-ToBeginner · 3 min read

How to Use ZREVRANGE in Redis: Syntax and Examples

Use the ZREVRANGE command in Redis to get elements from a sorted set ordered from highest to lowest score. Specify the key and the start and stop indexes to select the range of elements you want.
📐

Syntax

The ZREVRANGE command retrieves members in a sorted set ordered from highest to lowest score. You provide the key name, a start index, and a stop index. Indexes are zero-based, where 0 is the highest score member.

  • key: The name of the sorted set.
  • start: The starting index (0 is the top score).
  • stop: The ending index (inclusive).
  • Optionally, add WITHSCORES to get scores along with members.
redis
ZREVRANGE key start stop [WITHSCORES]
💻

Example

This example shows how to add members to a sorted set and then retrieve them in descending order by score using ZREVRANGE.

redis
127.0.0.1:6379> ZADD leaderboard 100 "Alice" 200 "Bob" 150 "Carol"
(integer) 3
127.0.0.1:6379> ZREVRANGE leaderboard 0 2 WITHSCORES
1) "Bob"
2) "200"
3) "Carol"
4) "150"
5) "Alice"
6) "100"
Output
1) "Bob" 2) "200" 3) "Carol" 4) "150" 5) "Alice" 6) "100"
⚠️

Common Pitfalls

Common mistakes when using ZREVRANGE include:

  • Using positive indexes without realizing they start from the highest score (0 is top, not bottom).
  • Confusing ZREVRANGE with ZRANGE which orders from lowest to highest score.
  • Forgetting that stop index is inclusive, so 0 2 returns three elements.
  • Not using WITHSCORES when scores are needed.

Example of wrong and right usage:

redis
127.0.0.1:6379> ZREVRANGE leaderboard 0 1
1) "Bob"
2) "Carol"

# Wrong: expecting only one element but got two because stop is inclusive

127.0.0.1:6379> ZREVRANGE leaderboard 0 0
1) "Bob"

# Correct: to get only the top element
📊

Quick Reference

ParameterDescription
keyName of the sorted set
startStart index (0 is highest score)
stopStop index (inclusive)
WITHSCORESOptional flag to return scores with members

Key Takeaways

ZREVRANGE returns sorted set members from highest to lowest score using zero-based indexes.
The start and stop indexes are inclusive and zero-based, where 0 is the top score member.
Use WITHSCORES to get both members and their scores in the result.
Remember ZREVRANGE is the reverse of ZRANGE, which orders from lowest to highest score.
Check indexes carefully to avoid off-by-one errors since stop is inclusive.