Redis SDIFFSTORE Command Explained

In Redis, the SDIFFSTORE command works just like the SDIFF command, except that instead of returning the result, it stores it in the key that we specify. The destination key will then hold the members of the set resulting from the difference between the first set and all the successive sets.

Syntax

The syntax goes like this:

SDIFFSTORE destination 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 SDIFFSTORE command to select all members from the first set that aren’t in the other sets, and put them in to a destination key called result1:

SDIFFSTORE result1 set1 set2 set3

Result:

(integer) 3

An integer reply of 3 is returned, which means that three members were added to the destination key.

Let’s check the contents of the result1 key:

SMEMBERS result1

Result:

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

So in this case only the values 2, 3 and 4 were added to the results1 key, because those are the only values that are present in the first set but not in the others. This is the same result that SDIFF would’ve returned if we had used that command instead.

Non-Existent Keys

Non-existent keys are treated as empty sets:

SDIFFSTORE results2 set1 set4 set5

Result:

(integer) 7

In this case, all members from set1 were added to the results2 key.

Let’s verify this:

SMEMBERS results2

Result:

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

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

SDIFFSTORE results3 set4 set1 set2 set3

Result:

(integer) 0

This time nothing is added to the results3 key, because set4 doesn’t contain anything that the others don’t contain (it doesn’t contain anything at all).