Script Valley
Redis: Complete Course
Core Commands and Data StructuresLesson 2.5

Redis Sorted Set commands: ZADD, ZRANGE, ZRANK, ZSCORE, ZRANGEBYSCORE

ZADD options NX XX GT LT, ZRANGE ZREVRANGE, ZRANK ZREVRANK, ZSCORE, ZRANGEBYSCORE, ZREM, ZINCRBY, leaderboard pattern

Sorted Sets for ranked data

A Sorted Set associates each member with a float score. Members are stored in ascending score order. Operations are O(log N).

Adding and updating

ZADD leaderboard 1500 "alice"
ZADD leaderboard 1200 "bob"
ZADD leaderboard 900  "carol"

# Increment alice's score
ZINCRBY leaderboard 100 "alice"   # → 1600

# Only update if new score is greater than current
ZADD leaderboard GT 1400 "bob"    # no-op, 1400 < 1200 is false

Querying ranks and scores

# Top 3, highest score first
ZRANGE leaderboard 0 2 REV WITHSCORES
# → [alice 1600, bob 1200, carol 900]

# Alice's rank (0-indexed, low to high)
ZRANK leaderboard "alice"     # → 2
ZREVRANK leaderboard "alice"  # → 0 (she's first)

# Score by member
ZSCORE leaderboard "bob"      # → 1200

Range by score

# Members scoring between 1000 and 2000
ZRANGEBYSCORE leaderboard 1000 2000
# → [bob, alice]

Sorted Sets are the canonical Redis leaderboard. They also power time-series indexes (score = Unix timestamp) and priority queues (score = priority).