Script Valley
Redis: Complete Course
Core Commands and Data StructuresLesson 2.4

Redis Set commands: SADD, SMEMBERS, SINTER, SUNION, SDIFF

SADD SREM, SMEMBERS SCARD, SISMEMBER, SINTER SUNION SDIFF, SMOVE, unique visitor tracking, tag systems

Sets for unique collections

A Set holds unique, unordered strings. Membership checks and add/remove are O(1). Set operations like intersection and union are O(N).

Core operations

SADD tags:post:1 "redis" "database" "cache"
SADD tags:post:2 "redis" "python"

SCARD tags:post:1         # → 3 (cardinality)
SISMEMBER tags:post:1 "redis"  # → 1 (exists)
SREM tags:post:1 "cache"  # removes one member

Set algebra

# Tags shared by both posts
SINTER tags:post:1 tags:post:2   # → ["redis"]

# All unique tags across both posts
SUNION tags:post:1 tags:post:2   # → ["redis","database","cache","python"]

# Tags in post:1 but NOT post:2
SDIFF tags:post:1 tags:post:2    # → ["database","cache"]

Unique visitor tracking

# Record that user 99 visited today
SADD visitors:2024-01-15 "99"

# Unique visitor count
SCARD visitors:2024-01-15

This pattern is simpler and faster than a SQL COUNT DISTINCT query. For very large sets where approximate counts are acceptable, use HyperLogLog (PFADD/PFCOUNT) instead — it uses constant 12 KB regardless of cardinality.

Up next

Redis Sorted Set commands: ZADD, ZRANGE, ZRANK, ZSCORE, ZRANGEBYSCORE

Sign in to track progress