w3resource

Redis Sets: SADD

SADD key member1 [member2]

Redis SADD command is used to add members to set stored at key. If the member already exists, then it is ignored. If the key does not exist, then a new set is created and members are added into it. If the value stored at key if not set, then an error is returned.

Here are some common uses and scenarios for the "SADD" command:

  • Adding Elements: Add one or more unique elements to a set.
  • Membership Management: Manage group memberships, like users in a group or tags on a resource.
  • Data Uniqueness: Ensure data uniqueness by adding elements to a set, as sets do not allow duplicate entries.
  • Dynamic Collections: Dynamically build collections of unique items, such as categories, tags, or identifiers.
  • Statistical Operations: Perform statistical operations by aggregating unique elements into sets for analysis.

Syntax:

SADD KEY_NAME VALUE1..VALUEN

Available since

1.0.0.

Return Value

Integer reply, the number of elements that were added to the set, not including all the elements already present into the set.

Return Value Type

Integer

Example: Redis SADD

127.0.0.1:6379> SADD mycolor "White"
(integer) 1
127.0.0.1:6379> SADD mycolor "Yellow" "Green"
(integer) 2
127.0.0.1:6379> SADD mycolor "Red" "Blue" "Orange"
(integer) 3
127.0.0.1:6379> SMEMBERS mycolor
1) "Yellow"
2) "White"
3) "Blue"
4) "Green"
5) "Red"
6) "Orange"

Example: Redis SADD : Not Allowed Duplicate Member

In the set, member can not be redundant.

127.0.0.1:6379> SADD mycolor "Orange"
(integer) 0
127.0.0.1:6379> SADD mycolor "Orange" "Pink"
(integer) 1
127.0.0.1:6379> SMEMBERS mycolor
1) "Blue"
2) "White"
3) "Yellow"
4) "Pink"
5) "Green"
6) "Red"
7) "Orange"

Previous: RPUSHX
Next: Redis Sets SCARD



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/redis/redis-sadd-key-member1.php