What is the difference between a Redis set and a Redis sorted set, and when would you choose one over the other?
Short answer
A set stores unique, unordered values and is ideal for membership checks like determining if an item exists in a collection, while a sorted set also stores unique values but each one has an associated numeric score that determines its order, making it the right choice whenever…
Advertisement
AModel answer
A set stores unique, unordered values and is ideal for membership checks like determining if an item exists in a collection, while a sorted set also stores unique values but each one has an associated numeric score that determines its order, making it the right choice whenever you need to rank items, such as a leaderboard or a list ordered by recency.
Example
SADD unique_visitors:today 'user123' ZADD leaderboard 1500 'user123'
Real-world example
An analytics system uses a regular set to track which unique visitors came to the site today, while using a sorted set for a leaderboard that ranks users by their accumulated points.
Likely follow-ups
- Can you convert a set into a sorted set later if you decide you need ordering?
- How does adding a score to every value affect memory usage compared to a plain set?
Related topics