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
2
3
4
5
6
7
8
9
10
11
12
13
127.0.0.1:6379> SADD s_db redis
(integer) 1
127.0.0.1:6379> SADD s_db hbase
(integer) 1
127.0.0.1:6379> SADD s_db mysql
(integer) 1
127.0.0.1:6379> SADD s_db mysql
(integer) 0
127.0.0.1:6379> SMEMBERS s_db
1) "mysql"
2) "hbase"
3) "redis"
127.0.0.1:6379>

Example 2

An error is returned when the value stored at key is not a set:

1
2
3
4
5
127.0.0.1:6379> SET name Johnson
OK
127.0.0.1:6379> SADD name Ella
(error) WRONGTYPE Operation against a key holding the wrong kind of value
127.0.0.1:6379>

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.