Sets & Sorted Sets: Overview
Two types, one concept: uniqueness
Section titled “Two types, one concept: uniqueness”Redis gives you two collection types that guarantee every member appears at most once:
| Type | Order | Extra data | Best for |
|---|---|---|---|
| Set | None (hash-table) | None | Tags, membership checks, set algebra |
| Sorted Set | By score (float64) | Score per member | Leaderboards, ranked feeds, range queries |
Both types store unique strings. The difference is that a Sorted Set attaches a floating-point score to each member, and keeps them sorted by that score at all times.
Sets at a glance
Section titled “Sets at a glance”A Set is an unordered collection of unique strings. Adding the same value twice has no effect.
127.0.0.1:6379> SADD lang:tags "python" "go" "rust" "go"(integer) 3127.0.0.1:6379> SMEMBERS lang:tags1) "rust"2) "go"3) "python"127.0.0.1:6379> SCARD lang:tags(integer) 3SADD lang:tags "python" "go" "rust" "go"
SMEMBERS lang:tags
SCARD lang:tagsSorted Sets at a glance
Section titled “Sorted Sets at a glance”A Sorted Set pairs each member with a score. Members are always retrieved in score order.
127.0.0.1:6379> ZADD scores 1500 "alice" 2200 "bob" 980 "carol"(integer) 3127.0.0.1:6379> ZRANGE scores 0 -1 WITHSCORES1) "carol"2) "980"3) "alice"4) "1500"5) "bob"6) "2200"127.0.0.1:6379> ZRANK scores "alice"(integer) 1ZADD scores 1500 "alice" 2200 "bob" 980 "carol"
ZRANGE scores 0 -1 WITHSCORES
ZRANK scores "alice"When to use each
Section titled “When to use each”- Set — you need to answer “is X a member?” or “what do A and B have in common?” quickly.
- Sorted Set — you need ordering, ranking, or range queries (e.g., “players with scores between 1000 and 2000”).
What this module covers
Section titled “What this module covers”| Lesson | Topic |
|---|---|
| Sets & Sorted Sets: Overview | This page — types and a quick taste |
| Sets | SADD, SREM, SMEMBERS, SISMEMBER, SCARD, SRANDMEMBER, SPOP |
| Set Operations | SINTER, SUNION, SDIFF and their STORE variants |
| Sorted Sets | ZADD, ZSCORE, ZRANGE, ZREVRANGE, ZRANK, ZRANGEBYSCORE, ZINCRBY, ZCARD, ZREM |
| Leaderboards | Building a real leaderboard with Sorted Sets |