What is Sorted Set (ZSet)?
A Sorted Set (ZSet) in Redis is a set of unique elements, where each element is tied to a numeric value, a "score". These elements are automatically kept sorted by score.
Main properties
- Every element is unique, just like in a regular Set.
- Every element has a score, a floating-point number.
- Elements are always ordered by score (ascending).
- Ranges can be fetched by position or by score.
Example
bash
ZADD rating 100 "anna" 200 "ivan" 150 "maria"
ZRANGE rating 0 -1 WITHSCORESResult:
javascript
1) "anna" (100)
2) "maria" (150)
3) "ivan" (200)Elements are automatically sorted by score.
Main commands
| Command | Description |
|---|---|
ZADD key score member [score member ...] | add elements with scores |
ZRANGE key start stop [WITHSCORES] | get elements by position (ascending) |
ZREVRANGE key start stop [WITHSCORES] | the same, but descending |
ZRANGEBYSCORE key min max [WITHSCORES] | get elements within a score range |
ZREM key member [member ...] | remove element(s) |
ZSCORE key member | get an element's score |
ZCARD key | the number of elements |
ZCOUNT key min max | the number of elements within a score range |
ZRANK key member | an element's ascending position |
ZREVRANK key member | an element's descending position |
ZINCRBY key increment member | increment an element's score |
A leaderboard example
bash
ZADD leaderboard 300 "player1"
ZADD leaderboard 500 "player2"
ZADD leaderboard 450 "player3"
ZREVRANGE leaderboard 0 2 WITHSCORESResult:
javascript
1) "player2" (500)
2) "player3" (450)
3) "player1" (300)This is how leaderboards, rankings, points, and task priorities get stored.
A score range
bash
ZRANGEBYSCORE leaderboard 400 600Result:
javascript
"player2"
"player3"Internal structure
A ZSet is implemented as a combination of:
- A Hash, for fast lookup of a score by an element's name.
- A Skip list, for keeping elements sorted.
That's what gives it O(log N) complexity for insertion, lookup, and deletion.
Uses
- Leaderboards, rankings.
- Priority queues.
- Event timestamps (time series).
- Tracking user activity.
- Task lists by priority or deadline.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.