You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Redis provides two set-based data structures. A Set is an unordered collection of unique strings. A Sorted Set (also called a ZSet) adds a floating-point score to each member, enabling ordered retrieval and range queries.
127.0.0.1:6379> SADD active_users "alice" "bob" "carol" "alice"
(integer) 3 # "alice" was deduplicated automatically
127.0.0.1:6379> SMEMBERS active_users
1) "carol"
2) "bob"
3) "alice"
127.0.0.1:6379> SCARD active_users
(integer) 3
127.0.0.1:6379> SISMEMBER active_users "bob"
(integer) 1 # 1 = member exists
127.0.0.1:6379> SMISMEMBER active_users "bob" "dan"
1) (integer) 1
2) (integer) 0
127.0.0.1:6379> SADD group_a "alice" "bob" "carol"
(integer) 3
127.0.0.1:6379> SADD group_b "bob" "carol" "dan"
(integer) 3
# Intersection — members in both sets
127.0.0.1:6379> SINTER group_a group_b
1) "carol"
2) "bob"
# Union — all unique members across both sets
127.0.0.1:6379> SUNION group_a group_b
1) "alice"
2) "bob"
3) "carol"
4) "dan"
# Difference — members in group_a but not group_b
127.0.0.1:6379> SDIFF group_a group_b
1) "alice"
127.0.0.1:6379> ZADD leaderboard 9850 "alice" 12200 "bob" 7600 "carol"
(integer) 3
# ZRANGE with WITHSCORES returns members lowest-score-first
127.0.0.1:6379> ZRANGE leaderboard 0 -1 WITHSCORES
1) "carol"
2) "7600"
3) "alice"
4) "9850"
5) "bob"
6) "12200"
# REV returns highest-score-first
127.0.0.1:6379> ZRANGE leaderboard 0 -1 WITHSCORES REV
127.0.0.1:6379> ZRANK leaderboard "alice"
(integer) 1 # zero-based rank, 0 = lowest score
127.0.0.1:6379> ZSCORE leaderboard "alice"
"9850"
Atomically increase a member's score — perfect for live leaderboard updates:
127.0.0.1:6379> ZINCRBY leaderboard 500 "carol"
"8100"
Retrieve members within a score range:
127.0.0.1:6379> ZRANGEBYSCORE leaderboard 8000 10000 WITHSCORES
1) "carol"
2) "8100"
3) "alice"
4) "9850"
Sorted Sets are the go-to structure for leaderboards, priority queues, time-series indexes, and any scenario requiring ordered data with fast range lookups.
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.