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
2
3
4
key1 = {a, b, c, d}
key2 = {c}
key3 = {a, c, e}
SDIFF key1 key2 key3 = {b, 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
2
3
4
5
6
7
8
9
10
127.0.0.1:6379> SADD key1 a b c d
(integer) 4
127.0.0.1:6379> SADD key2 c
(integer) 1
127.0.0.1:6379> SADD key3 a c e
(integer) 3
127.0.0.1:6379> SDIFF key1 key2 key3
1) "b"
2) "d"
127.0.0.1:6379>

Step-by-step breakdown:

  • The first set is key1 = {a, b, c, d}.
  • The second set is key2 = {c} and the third set is key3 = {a, c, e}.
  • Now, we check which elements in key1 are not in key2 or key3:
    • a: Found in key3, so it’s excluded.
    • b: Not found in key2 or key3, so it remains.
    • c: Found in both key2 and key3, so it’s excluded.
    • d: Not found in key2 or key3, so it remains.
  • The difference between key1 and the other two sets is {b, d}.