How to Use SUNION Command in Redis for Set Union
Use the
SUNION command in Redis to get the union of multiple sets, which returns all unique members from the given sets. The syntax is SUNION key1 key2 ..., where each key is a set name.Syntax
The SUNION command combines all members from the specified sets and returns a list of unique elements.
key1, key2, ...: Names of the sets to union.- The result contains all unique members from these sets.
redis
SUNION key1 key2 [key3 ...]
Example
This example shows how to create two sets and use SUNION to get all unique members from both.
redis
SADD fruits apple banana orange SADD tropical mango banana pineapple SUNION fruits tropical
Output
1) "apple"
2) "banana"
3) "orange"
4) "mango"
5) "pineapple"
Common Pitfalls
Common mistakes include:
- Using
SUNIONon keys that are not sets, which causes errors. - Expecting
SUNIONto modify sets; it only returns the union without changing data. - Confusing
SUNIONwithSUNIONSTORE, which stores the result in a new set.
redis
/* Wrong: Using SUNION on a string key */ SET key1 "value" SUNION key1 fruits /* Right: Use only set keys */ SADD key1 a b c SADD key2 b c d SUNION key1 key2
Output
(error) WRONGTYPE Operation against a key holding the wrong kind of value
1) "a"
2) "b"
3) "c"
4) "d"
Quick Reference
| Command | Description |
|---|---|
| SUNION key1 key2 ... | Returns the union of all given sets |
| SUNIONSTORE dest key1 key2 ... | Stores the union of sets into destination key |
| SADD key member [member ...] | Adds members to a set |
| SMEMBERS key | Returns all members of a set |
Key Takeaways
SUNION returns all unique members from multiple sets without modifying them.
Only use SUNION with keys that hold sets to avoid errors.
SUNION does not store results; use SUNIONSTORE to save the union.
The command syntax is simple: SUNION followed by set keys.
Use SADD to create sets before using SUNION.