Redis Sets (Part 2)
This lesson covers set intersection, union, and difference operations — the most powerful features of sets.
Set Operations Overview
Redis supports three set operations:
| Operation | Description | Command |
|---|---|---|
| Intersection | Elements present in all sets | SINTER |
| Union | Elements present in any set | SUNION |
| Difference | Elements in the first set but not in others | SDIFF |
Set A: {1, 2, 3, 4}
Set B: {3, 4, 5, 6}
Intersection A∩B: {3, 4}
Union A∪B: {1, 2, 3, 4, 5, 6}
Difference A-B: {1, 2}
SINTER: Intersection
Intersection returns elements that exist in all specified sets.
Basic Usage
REDIS
# Create two sets
SADD set1 "a" "b" "c" "d"
SADD set2 "c" "d" "e" "f"
# Calculate intersection
SINTER set1 set2
1) "c"
2) "d"
Intersection of Multiple Sets
REDIS
SADD set3 "c" "d" "g"
# Intersection of three sets
SINTER set1 set2 set3
1) "c"
2) "d"
Non-existent Set
REDIS
# If a set does not exist, it is treated as empty
SINTER set1 notexist
(empty array)
SINTERCARD: Intersection Cardinality (Redis 7.0+)
REDIS
SINTERCARD 2 set1 set2
(integer) 2 # Intersection has 2 elements
SUNION: Union
Union returns elements that exist in any of the sets.
Basic Usage
REDIS
SADD set1 "a" "b" "c"
SADD set2 "c" "d" "e"
# Calculate union
SUNION set1 set2
1) "a"
2) "b"
3) "c"
4) "d"
5) "e"
Union of Multiple Sets
REDIS
SADD set3 "e" "f" "g"
# Union of three sets
SUNION set1 set2 set3
1) "a"
2) "b"
3) "c"
4) "d"
5) "e"
6) "f"
7) "g"
SDIFF: Difference
Difference returns elements that are in the first set but not in any of the other sets.
Basic Usage
REDIS
SADD set1 "a" "b" "c" "d"
SADD set2 "c" "d" "e" "f"
# set1 - set2
SDIFF set1 set2
1) "a"
2) "b"
Difference of Multiple Sets
REDIS
SADD set3 "a" "g"
# set1 - set2 - set3
SDIFF set1 set2 set3
1) "b" # a is in set3, so it's excluded
⚠️ Note: Difference is not commutative.
SDIFF A B ≠ SDIFF B A.
Storing Set Operation Results
SINTERSTORE: Store Intersection Result
REDIS
SADD set1 "a" "b" "c" "d"
SADD set2 "c" "d" "e" "f"
# Store intersection result in a new set
SINTERSTORE result set1 set2
(integer) 2 # Result set has 2 elements
SMEMBERS result
1) "c"
2) "d"
SUNIONSTORE: Store Union Result
REDIS
SUNIONSTORE result set1 set2
(integer) 6
SMEMBERS result
1) "a"
2) "b"
3) "c"
4) "d"
5) "e"
6) "f"
SDIFFSTORE: Store Difference Result
REDIS
SDIFFSTORE result set1 set2
(integer) 2
SMEMBERS result
1) "a"
2) "b"
💡 Use case: *STORE commands save results to new sets for subsequent operations or caching.
Set Operation Use Cases
Use Case 1: Mutual Friends
REDIS
# User 1's friends
SADD user:1:friends "user:2" "user:3" "user:4" "user:5"
# User 2's friends
SADD user:2:friends "user:3" "user:4" "user:6" "user:7"
# Mutual friends
SINTER user:1:friends user:2:friends
1) "user:3"
2) "user:4"
Use Case 2: People You May Know
REDIS
# My friends
SADD user:1:friends "user:2" "user:3"
# Friends of friends
SADD user:2:friends "user:3" "user:4" "user:5"
SADD user:3:friends "user:4" "user:6"
# Union of friends of friends
SUNIONSTORE friends:friends user:2:friends user:3:friends
# Recommended friends = friends of friends - my friends - me
SADD me "user:1"
SUNIONSTORE exclude me user:1:friends
SDIFF friends:friends exclude
Use Case 3: Article Recommendation
REDIS
# User's liked tags
SADD user:1:liked:tags "redis" "database" "cache"
# Article tags
SADD article:123:tags "redis" "nosql"
SADD article:456:tags "mysql" "database"
SADD article:789:tags "redis" "cache" "performance"
# Recommend articles that match user interests (tag intersection)
SINTER user:1:liked:tags article:123:tags
1) "redis" # article:123 matches 1 tag
SINTER user:1:liked:tags article:789:tags
1) "redis"
2) "cache" # article:789 matches 2 tags — stronger recommendation
Use Case 4: Product Filtering
REDIS
# Product categories
SADD category:phone "product:1" "product:2" "product:3"
SADD category:laptop "product:4" "product:5"
# Product brands
SADD brand:apple "product:1" "product:4"
SADD brand:samsung "product:2" "product:5"
# Filter: phone + Apple brand
SINTER category:phone brand:apple
1) "product:1"
Use Case 5: Permission Checking
REDIS
# User permissions
SADD user:1:permissions "read" "write" "delete"
# Resource required permissions
SADD resource:123:required "read" "write"
# Check if user has all required permissions
SINTER user:1:permissions resource:123:required
1) "read"
2) "write"
# If result count equals required permissions count, user is authorized
Use Case 6: Tag Aggregation
REDIS
# Article tags
SADD article:1:tags "redis" "database"
SADD article:2:tags "redis" "cache"
SADD article:3:tags "mysql" "database"
# All tags
SUNIONSTORE all:tags article:1:tags article:2:tags article:3:tags
SMEMBERS all:tags
1) "redis"
2) "database"
3) "cache"
4) "mysql"
Set Operation Performance
Time Complexity
| Command | Time Complexity | Description |
|---|---|---|
| SINTER | O(N*M) | N = smallest set size, M = number of sets |
| SUNION | O(N) | N = total elements across all sets |
| SDIFF | O(N) | N = total elements across all sets |
⚠️ Performance tip: Set operations traverse all elements. Large sets can be slow. Recommendations:
- Use SINTERCARD instead of SINTER (only returns count)
- Cache results (use *STORE commands)
- Limit set sizes
SSCAN: Iterate Large Sets
For large sets, use SSCAN to iterate through elements in batches.
REDIS
# Create a large set
SADD large:set value1 value2 ... value10000
# Start iteration
SSCAN large:set 0
1) "127" # Cursor for next iteration
2) 1) "value1"
2) "value2"
...
# Continue iteration
SSCAN large:set 127
1) "0" # Cursor of 0 means iteration is complete
2) ...
Match Pattern
REDIS
# Get only elements matching a pattern
SSCAN large:set 0 MATCH user:*
Set Limitations
1. Unordered
REDIS
# Cannot get elements in a specific order
SMEMBERS myset # Return order is undefined
For ordered data, use Sorted Sets.
2. Strings Only
REDIS
# Set elements can only be strings
SADD myset 123 # Stores the string "123"
3. No Nested Structures
Sets do not support nested sets or objects.
❓ FAQ
Q What's the difference between SINTER and SINTERSTORE?
A SINTER returns the intersection result; SINTERSTORE stores the result in a new set.
Q Is difference commutative?
A No.
SDIFF A B ≠ SDIFF B A. Order matters.Q Do set operations modify the original sets?
*A: No. SINTER/SUNION/SDIFF are read-only. STORE commands overwrite the destination set.
Q: How do I count the intersection size without getting elements?
A Use SINTERCARD (Redis 7.0+), or use SINTER + count the results.
Q How fast are set operations?
A It depends on set size. Large set operations can be slow — limit set sizes or use caching.
📖 Summary
- SINTER: elements present in all sets
- SUNION: elements present in any set
- SDIFF: elements in the first set but not others
- *STORE commands save operation results to new sets
- Set operations for: mutual friends, recommendations, filtering, permission checks
- Performance: large set operations are slow — cache or limit sizes
- SSCAN iterates large sets to avoid blocking
📝 Exercises
- Mutual friends: Create two users' friend lists and find mutual friends
- Recommendation system: Implement a simple article recommendation system based on user interest tags
- Product filtering: Use sets for multi-condition product filtering (category + brand)
- Permission check: Use set operations to check if a user has all required permissions for a resource
Next Lesson
In the next lesson, we will learn Redis Sorted Sets (Part 1), covering basic sorted set operations.



