Video in progress
What is the difference between a Set and a Sorted Set, and when do you need each?
A Set is an unordered collection without duplicates. In a Sorted Set every element has a score and the elements are kept ordered by it, so "top 10" and range queries are fast.
📖 Answer
A Set example, the users who liked a post:
SADD post:5:likes user:1 user:2 user:1 # user:1 is not added twice
SCARD post:5:likes # 2
SISMEMBER post:5:likes user:2 # 1
Sets also have SINTER, SUNION and SDIFF, for example to find the mutual friends of two users.
A Sorted Set example, a game leaderboard:
ZINCRBY leaderboard 50 user:1
ZREVRANGE leaderboard 0 9 WITHSCORES # the top 10
ZRANK leaderboard user:1
Sorted Sets are also used for time-based data: put a timestamp in as the score and use ZRANGEBYSCORE to get the elements "from the last 5 minutes". Adding and removing are O(log N).
Sign up to mark studied questions and save your progress.