Skip to content
ZADD, ZSCORE & ZRANGE — Sorted Sets
step 1/3

Reading — step 1 of 3

Sorted Sets

~1 min readSets & Sorted Sets

ZADD, ZSCORE & ZRANGE — Sorted Sets

Sorted sets combine the uniqueness of sets with an ordering score. Every member has an associated floating-point score.

Commands

  • ZADD key score member [score member ...] — add with scores, return count of NEW
  • ZSCORE key member — return score as bulk string, or $-1
  • ZRANGE key start stop [WITHSCORES] — return members ordered by score (low→high)
  • ZRANK key member — return 0-based rank (position by score), or $-1
  • ZCARD key — return count

Use Cases

Sorted sets are one of Redis's most powerful features:

  • Leaderboards: ZADD leaderboard 1500 alice 2000 bob
  • Priority queues: score = priority
  • Time-based feeds: score = timestamp
  • Rate limiting: score = request timestamp

Implementation

You need a data structure that maintains order by score. Options:

  • Simple: List of (score, member) tuples, sorted on insert
  • Efficient: Skip list + hash map (what Redis actually uses)

For this exercise, the simple approach is fine — we're not benchmarking performance.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…