How to Use SDIFF in Redis: Syntax and Examples
Use the
SDIFF command in Redis to get members of the first set that are not in the other sets. The syntax is SDIFF key1 key2 [key3 ...], where it returns all elements in key1 that do not exist in the other specified sets.Syntax
The SDIFF command takes one or more set keys and returns the members of the first set that are not present in any of the other sets.
- key1: The key of the first set to compare.
- key2, key3, ...: Other set keys to compare against.
The result is a set of elements unique to key1.
redis
SDIFF key1 key2 [key3 ...]
Example
This example shows how to find elements in the set fruits that are not in the set citrus.
redis
SADD fruits apple banana orange mango SADD citrus orange lemon lime SDIFF fruits citrus
Output
1) "apple"
2) "banana"
3) "mango"
Common Pitfalls
Common mistakes when using SDIFF include:
- Using keys that do not exist, which returns an empty set.
- Expecting
SDIFFto modify sets; it only returns the difference without changing data. - Confusing
SDIFFwithSDIFFSTORE, which stores the result in a new set.
redis
;; Wrong: expecting SDIFF to change sets SDIFF fruits citrus SMEMBERS fruits ;; Right: SDIFF only returns difference SDIFF fruits citrus ;; To store difference use SDIFFSTORE SDIFFSTORE unique_fruits fruits citrus SMEMBERS unique_fruits
Output
1) "apple"
2) "banana"
3) "mango"
1) "apple"
2) "banana"
3) "orange"
4) "mango"
1) "apple"
2) "banana"
3) "mango"
Quick Reference
| Command | Description |
|---|---|
| SDIFF key1 key2 [key3 ...] | Returns members of key1 not in other sets |
| SDIFFSTORE dest key1 key2 [key3 ...] | Stores the difference in dest set |
| SADD key member [member ...] | Adds members to a set |
| SMEMBERS key | Returns all members of a set |
Key Takeaways
SDIFF returns members in the first set that are not in the other sets.
SDIFF does not modify any sets; it only returns the difference.
Use SDIFFSTORE to save the difference into a new set.
If any key does not exist, it is treated as an empty set.
Always check your keys exist to avoid unexpected empty results.