Redis SDIFF Command Explained

In Redis, the SDIFF command returns the members of the set resulting from the difference between the first set and all the successive sets. In other words, it returns all members of the first set that aren’t in any of the successive sets.

Syntax

The syntax goes like this:

SDIFF key [key ...]

Example

Suppose we create the following sets:

SADD set1 0 1 2 3 4 5 6
SADD set2 5 6 7 8
SADD set3 0 1 7 8

We can use the SDIFF command to return all members from the first set that aren’t in the other sets:

SDIFF set1 set2 set3

Result:

1) "2"
2) "3"
3) "4"

As expected, only the values 2, 3 and 4 are returned, because those are the only values that are present in the first set but not in the others.

Non-Existent Keys

Non-existent keys are treated as empty sets:

SDIFF set1 set4 set5

Result:

1) "0"
2) "1"
3) "2"
4) "3"
5) "4"
6) "5"
7) "6"

In our case, set4 and set5 don’t actually exist, and so they’re treated as empty sets. The result is that all members of set1 are returned, because all of its members are not present in the other sets.

Let’s see what happens when the first key is non-existent:

SDIFF set4 set1 set2 set3

Result:

(empty array)

This time we get an empty array, because set4 doesn’t contain anything that the others don’t contain. That’s because it doesn’t contain anything at all.