0
0
Redisquery~5 mins

Why sorted sets solve ranking problems in Redis

Choose your learning style9 modes available
Introduction

Sorted sets help keep items in order by score, making it easy to find top or bottom ranked items quickly.

When you want to show a leaderboard of top players in a game.
When you need to rank products by popularity or rating.
When tracking the most recent or highest scored posts in a social app.
When you want to quickly find the highest or lowest values in a list.
When you need to update rankings dynamically as scores change.
Syntax
Redis
ZADD key score member [score member ...]
ZRANGE key start stop [WITHSCORES]
ZREVRANGE key start stop [WITHSCORES]

ZADD adds members with scores to the sorted set.

ZRANGE gets members in ascending order by score.

ZREVRANGE gets members in descending order by score.

Examples
Adds three players with their scores to the leaderboard sorted set.
Redis
ZADD leaderboard 100 "Alice" 200 "Bob" 150 "Carol"
Gets all players from lowest to highest score with their scores.
Redis
ZRANGE leaderboard 0 -1 WITHSCORES
Gets the top two players with the highest scores.
Redis
ZREVRANGE leaderboard 0 1 WITHSCORES
Sample Program

This adds three players with scores and then retrieves the top 3 players by score in descending order.

Redis
ZADD leaderboard 100 "Alice" 200 "Bob" 150 "Carol"
ZREVRANGE leaderboard 0 2 WITHSCORES
OutputSuccess
Important Notes

Sorted sets automatically keep members ordered by score, so you don't need to sort manually.

Scores can be updated easily with ZADD, and the order updates automatically.

Using WITHSCORES option helps see both members and their scores together.

Summary

Sorted sets store items with scores to keep them ordered.

This makes ranking tasks like leaderboards simple and fast.

Commands like ZADD and ZREVRANGE help add and retrieve ranked data easily.