Skip to main content

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 WITHSCORES

Result:

javascript
1) "anna" (100) 2) "maria" (150) 3) "ivan" (200)

Elements are automatically sorted by score.

Main commands

CommandDescription
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 memberget an element's score
ZCARD keythe number of elements
ZCOUNT key min maxthe number of elements within a score range
ZRANK key memberan element's ascending position
ZREVRANK key memberan element's descending position
ZINCRBY key increment memberincrement an element's score

A leaderboard example

bash
ZADD leaderboard 300 "player1" ZADD leaderboard 500 "player2" ZADD leaderboard 450 "player3" ZREVRANGE leaderboard 0 2 WITHSCORES

Result:

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 600

Result:

javascript
"player2" "player3"

Internal structure

A ZSet is implemented as a combination of:

  1. A Hash, for fast lookup of a score by an element's name.
  2. 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 ready
Premium

A concise answer to help you respond confidently on this topic during an interview.