How do sorted sets differ from regular sets, and what additional capability does the associated score provide?
Short answer
A sorted set also guarantees unique members like a regular set, but additionally associates a numeric score with each member, which Redis uses to automatically maintain the members in a consistently sorted order, enabling powerful range based queries and ranking operations that…
Advertisement
AModel answer
A sorted set also guarantees unique members like a regular set, but additionally associates a numeric score with each member, which Redis uses to automatically maintain the members in a consistently sorted order, enabling powerful range based queries and ranking operations that a regular unordered set simply cannot support.
Example
ZADD scores 85 'alice' ZADD scores 92 'bob' ZRANGE scores 0 -1 WITHSCORES -- returns sorted by score
Real-world example
A quiz application stores participant scores in a sorted set, automatically keeping everyone ranked by their score and letting the application instantly retrieve the current standings without any manual sorting logic.
Likely follow-ups
- Can two different members have the exact same score in a sorted set?
- How does Redis handle sorting when two members do share the same score?
Related topics