In Redis, the SUNION
command returns the members of the set resulting from the union of all of the given sets.
Syntax
The syntax goes like this:
SUNION key [key ...]
We can pass one or more keys to the command.
Example
Suppose we create the following sets:
SADD cats Fluffy Scratch Meow
SADD dogs Wag Bark Fluffy
We can use SUNION
to return the union of those two sets:
SUNION cats dogs
Result:
1) "Bark" 2) "Scratch" 3) "Fluffy" 4) "Meow" 5) "Wag"
Note that duplicate values are only included once. This makes sense, because sets can only contain unique values, and the result of SUNION
is a set. In our example, Fluffy
appears in both the cats
and dogs
sets, but it only appears once in the set resulting from SUNION
.
Non-Existent Sets
Sets that don’t exist are treated as empty sets:
SUNION cats dogs elephants
Result:
1) "Bark" 2) "Scratch" 3) "Fluffy" 4) "Meow" 5) "Wag"
Here, we added a third set called elephants
, but that set doesn’t exist. The result is the same as the previous example.
Union of a Single Set
If we pass a single set, we simply get the members of that set:
SUNION cats
Result:
1) "Meow" 2) "Scratch" 3) "Fluffy"
Wrong Argument Count
Calling SUNION
without any arguments results in an error:
SUNION
Result:
(error) ERR wrong number of arguments for 'sunion' command