How to Use SADD Command in Redis: Add Members to a Set
Use the
SADD command in Redis to add one or more members to a set stored at a key. It creates the set if it does not exist and returns the number of new members added.Syntax
The SADD command adds one or more members to a set stored at a given key. If the key does not exist, Redis creates a new set. The command returns the number of elements that were added to the set, excluding members that were already present.
key: The name of the set.member [member ...]: One or more values to add to the set.
redis
SADD key member [member ...]
Example
This example shows how to add members to a set named fruits. It adds three fruits and then tries to add one that already exists.
redis
127.0.0.1:6379> SADD fruits apple banana cherry (integer) 3 127.0.0.1:6379> SADD fruits banana orange (integer) 1 127.0.0.1:6379> SMEMBERS fruits 1) "apple" 2) "banana" 3) "cherry" 4) "orange"
Output
(integer) 3
(integer) 1
1) "apple"
2) "banana"
3) "cherry"
4) "orange"
Common Pitfalls
Common mistakes when using SADD include:
- Trying to add duplicate members expecting the count to increase. Redis only counts new unique members.
- Using
SADDon keys holding other data types causes errors. - Not checking the return value to confirm how many members were actually added.
redis
127.0.0.1:6379> SET fruits "not a set" OK 127.0.0.1:6379> SADD fruits apple (error) WRONGTYPE Operation against a key holding the wrong kind of value -- Correct usage: 127.0.0.1:6379> DEL fruits (integer) 1 127.0.0.1:6379> SADD fruits apple (integer) 1
Output
(error) WRONGTYPE Operation against a key holding the wrong kind of value
(integer) 1
Quick Reference
| Command | Description |
|---|---|
| SADD key member [member ...] | Add one or more members to a set |
| SMEMBERS key | Get all members of the set |
| SREM key member | Remove a member from the set |
| SCARD key | Get the number of members in the set |
Key Takeaways
Use SADD to add unique members to a Redis set; it creates the set if missing.
SADD returns the count of new members added, ignoring duplicates.
Avoid using SADD on keys holding non-set data types to prevent errors.
Check the return value to confirm how many members were actually added.
Use SMEMBERS to view all members of a set after adding.