Difficulty: Beginner
How do you find the elements common to two Redis Sets, all unique elements across them, or the elements in one but not the other?
Use SINTER set1 set2 for the intersection (elements in both), SUNION set1 set2 for the union (every unique element), and SDIFF set1 set2 for the difference (elements in set1 that are not in set2). Each has a STORE variant (SINTERSTORE, SUNIONSTORE, SDIFFSTORE) that saves the result into a new key instead of returning it, and Redis 7.0 added SINTERCARD to count the intersection without transferring it.
| Command | Returns | Time complexity |
|---|---|---|
SINTER a b ... | Members present in all sets | O(N*M) worst case, N = smallest set size, M = number of sets |
SUNION a b ... | Members present in any set | O(N), N = total members across sets |
SDIFF a b ... | Members of a not in any later set | O(N), N = total members across sets |
SINTERCARD n a b ... [LIMIT k] | Size of the intersection (7.0+) | Like SINTER, can stop early at LIMIT |
S*STORE dest ... | Writes result to dest, returns its size | Same as the read version |
SDIFF is the only order-sensitive one: SDIFF a b and SDIFF b a differ. A missing key is treated as an empty set, so SINTER with any missing key returns an empty result.
SINTER followers:asha followers:ravi.tag:5g, brand:samsung, price:under-20k holding product IDs; SINTER gives the products matching all filters.SDIFF users:active users:opted_out gives the users you are allowed to message.SUNION visitors:2026-10-10 visitors:2026-10-11 (or HyperLogLog if you only need an approximate count).SINTERCARD 2 cart:42 blocked:skus LIMIT 1 returns 1 as soon as one blocked item is found.SUNION across sets with millions of members returns a huge reply and blocks the server while building it. Use STORE with an expiry and paginate with SSCAN, or precompute.CROSSSLOT error. Use hash tags: followers:{asha} and following:{asha} land on the same slot because only the part inside braces is hashed.ZINTER / ZUNION (6.2+) or their STORE versions with weights.SINTERSTORE creates a normal key; add EXPIRE if it is a cache.| Command | Result | |
|---|---|---|
| Intersection | SINTER asha neha | meera, kabir |
| Union | SUNION asha neha | ravi, meera, kabir, dev |
| Difference | SDIFF asha neha | ravi |
| Count only | SINTERCARD 2 asha neha | 2 |
SADD followers:asha ravi meera kabir
SADD followers:neha meera kabir dev
SINTER followers:asha followers:neha
SUNION followers:asha followers:neha
SDIFF followers:asha followers:neha
SINTERCARD 2 followers:asha followers:neha
# Save the mutual followers for 10 minutes
SINTERSTORE mutual:asha followers:asha followers:neha
EXPIRE mutual:asha 600
Member order in set replies is not guaranteed. In Redis Cluster these keys would need a shared hash tag, such as followers:{social}:asha, to avoid a CROSSSLOT error.
SINTER, SUNION, SDIFF, SINTERCARD, Hash tags in Cluster