0
0
Redisquery~5 mins

Why sorted sets combine uniqueness with ordering in Redis

Choose your learning style9 modes available
Introduction

Sorted sets in Redis let you store unique items and keep them in order at the same time. This helps you quickly find items by their rank or score.

When you want to keep a list of top scores in a game without duplicates.
When you need to show items sorted by time or priority and avoid repeats.
When you want to rank users by points and get their position easily.
When you want to store unique tags with a weight and retrieve them sorted.
When you want to combine fast lookups with sorted results.
Syntax
Redis
ZADD key [NX|XX] [CH] [INCR] score member [score member ...]
ZADD adds members with scores to a sorted set, keeping members unique.
If a member exists, its score is updated, keeping uniqueness and order.
Examples
Adds three unique members with scores to the sorted set 'leaderboard'.
Redis
ZADD leaderboard 100 "Alice" 200 "Bob" 150 "Carol"
Updates Alice's score to 250, keeping her unique and reordering the set.
Redis
ZADD leaderboard 250 "Alice"
Adds Dave only if he is not already in the set (NX means no update if exists).
Redis
ZADD leaderboard NX 300 "Dave"
Sample Program

This adds three fruits with scores, updates banana's score, then lists all items sorted by score.

Redis
ZADD scores 10 "apple" 20 "banana" 15 "cherry"
ZADD scores 25 "banana"
ZRANGE scores 0 -1 WITHSCORES
OutputSuccess
Important Notes

Sorted sets keep members unique by name but order them by score.

Updating a member's score changes its position in the order.

Use ZRANGE to get members in order with their scores.

Summary

Sorted sets combine uniqueness and ordering by storing unique members with scores.

This allows fast ranking and retrieval of items in sorted order.

Updating scores reorders members without duplicates.