Redis Set SDIFF Command
The Redis SDIFF command returns the difference between the first set and the other sets, which can be thought of as the elements unique to the first set. If any of the set keys do not exist, they are treated as empty sets.
For example, assume we have three sets: the first set contains the elements a, b, c, and d; the second set contains only c; and the third set contains a, c, and e. The result of the SDIFF key1 key2 key3 command is {b, d}, which consists of the elements from key1 that are not present in either key2 or key3.
| 1 | key1 = {a, b, c, d} | 
Syntax
The basic syntax of the SDIFF command is as follows:
| 1 | SDIFF key [key ...] | 
Available Since
Redis version >= 1.0.0
Time Complexity
O(N) where N is the total number of elements in all given sets.
ACL Categories
@read, @set, @slow
Return Value
Returns a set with the members of the resulting set.
Example
The SDIFF command returns the elements that are present in the first set (key1) but not in any of the other sets (key2, key3). Specifically, it checks: Which elements in key1 do not appear in key2 or key3.
| 1 | 127.0.0.1:6379> SADD key1 a b c d | 
Step-by-step breakdown:
- The first set is key1 = {a, b, c, d}.
- The second set is key2 = {c}and the third set iskey3 = {a, c, e}.
- Now, we check which elements in key1are not inkey2orkey3:- a: Found in- key3, so it’s excluded.
- b: Not found in- key2or- key3, so it remains.
- c: Found in both- key2and- key3, so it’s excluded.
- d: Not found in- key2or- key3, so it remains.
 
- The difference between key1and the other two sets is{b, d}.


