Redis Set SADD Command
The Redis SADD
command adds one or more member elements to a set. If an element already exists in the set, it will be ignored.
If the set key does not exist, a new set is created with the added elements as its members.
If the key is not of the set type, an error is returned.
Note: In Redis version 2.4 and earlier, the SADD
command only accepts a single member value.
Syntax
The basic syntax of the SADD
command is as follows:
1 | SADD key member [member ...] |
Available Since
Redis version >= 1.0.0
Time Complexity
- O(1) for each element added,
- O(N) to add N elements when the command is called with multiple arguments.
ACL Categories
@write
, @set
, @fast
Return Value
The number of new elements added to the set, excluding any elements that were ignored (i.e., already present in the set).
Example 1
1 | 127.0.0.1:6379> SADD s_db redis |
Example 2
An error is returned when the value stored at key is not a set:
1 | 127.0.0.1:6379> SET name Johnson |
In the example above, we used the SADD
command to add elements to the set named “name.” Redis throws an exception because the operation is attempted on a key holding the wrong type of value.