Skip to content

Set Operations

Redis can compute intersection, union, and difference between two or more Sets entirely on the server. You never need to pull all members to the client and compute locally.

SINTER key [key ...] returns only the members that appear in every listed Set. Classic use case: mutual friends.

127.0.0.1:6379> SADD user:1:follows "alice" "bob" "carol" "dave"
(integer) 4
127.0.0.1:6379> SADD user:2:follows "bob" "carol" "eve" "frank"
(integer) 4
127.0.0.1:6379> SINTER user:1:follows user:2:follows
1) "bob"
2) "carol"
SADD user:1:follows "alice" "bob" "carol" "dave"
SADD user:2:follows "bob" "carol" "eve" "frank"
SINTER user:1:follows user:2:follows

SUNION key [key ...] returns all members from any of the listed Sets, deduplicated. Use case: combined audience across campaigns.

127.0.0.1:6379> SADD campaign:A "user:1" "user:2" "user:3"
(integer) 3
127.0.0.1:6379> SADD campaign:B "user:2" "user:4" "user:5"
(integer) 3
127.0.0.1:6379> SUNION campaign:A campaign:B
1) "user:1"
2) "user:2"
3) "user:3"
4) "user:4"
5) "user:5"
SADD campaign:A "user:1" "user:2" "user:3"
SADD campaign:B "user:2" "user:4" "user:5"
SUNION campaign:A campaign:B

SDIFF key [key ...] returns members in the first Set that do not appear in any subsequent Set. Use case: find users in one group but not another.

127.0.0.1:6379> SADD plan:premium "user:1" "user:2" "user:3"
(integer) 3
127.0.0.1:6379> SADD notified:promo "user:2" "user:3"
(integer) 2
127.0.0.1:6379> SDIFF plan:premium notified:promo
1) "user:1"
SADD plan:premium "user:1" "user:2" "user:3"
SADD notified:promo "user:2" "user:3"
SDIFF plan:premium notified:promo

The *STORE variants write the result to a destination key instead of returning it. The destination is a regular Set you can inspect later.

127.0.0.1:6379> SADD group:eng "alice" "bob" "carol"
(integer) 3
127.0.0.1:6379> SADD group:ops "carol" "dave"
(integer) 2
127.0.0.1:6379> SINTERSTORE overlap:eng-ops group:eng group:ops
(integer) 1
127.0.0.1:6379> SMEMBERS overlap:eng-ops
1) "carol"
127.0.0.1:6379> SUNIONSTORE all:staff group:eng group:ops
(integer) 4
127.0.0.1:6379> SMEMBERS all:staff
1) "alice"
2) "bob"
3) "carol"
4) "dave"
SADD group:eng "alice" "bob" "carol"
SADD group:ops "carol" "dave"
SINTERSTORE overlap:eng-ops group:eng group:ops
SMEMBERS overlap:eng-ops
SUNIONSTORE all:staff group:eng group:ops
SMEMBERS all:staff
Which command returns members present in ALL listed sets?
What does SDIFF key1 key2 return?
What is the effect of SINTERSTORE destination key1 key2?
SUNION across two sets with some overlapping members returns how many copies of a shared member?