Redis SREM Command Explained

In Redis, the SREM command allows us to remove one or more members from a set.

Syntax

The syntax goes like this:

SREM key member [member ...]

So the command removes the specified member/s from the specified key.

Example

Suppose we create the following set:

SADD animals Cat Dog Cow Horse Bird Zebra

First, let’s use SMEMBERS to see all the members of the set:

SMEMBERS animals

Result:

1) "Dog"
2) "Cow"
3) "Cat"
4) "Horse"
5) "Zebra"
6) "Bird"

Now let’s use the SREM command to remove a member from that set:

SREM animals Cow

Result:

(integer) 1

In this case I removed just one member from the set.

Let’s check the set:

SMEMBERS animals

Result:

1) "Cat"
2) "Horse"
3) "Dog"
4) "Zebra"
5) "Bird"

We can see that the specified member (Cow) has been removed from the set.

Delete Multiple Members

As the above syntax shows, we can remove multiple members by specifying each one when we call the command.

Let’s run it again, but this time we’ll remove multiple members from the set:

SREM animals Cat Dog

Result:

(integer) 2

This time we get an integer reply of 2, which means that two members were removed.

Non-Existent Members

Specifying a member that doesn’t exist in the set results in an integer reply of 0:

SREM animals Buffalo

Result:

(integer) 0

Of course, if we also specify members that do exist, then we’ll get an integer reply that reflects the number of members that were removed:

SREM animals Buffalo Zebra

Result:

(integer) 1

In this case, Buffalo wasn’t in the set, but Zebra was. Therefore, Zebra was deleted and we got an integer reply of 1.

Wrong Argument Count

Passing the wrong number of arguments results in an error. This could happen if we forget to include a member to remove from the set:

SREM animals

Result:

(error) ERR wrong number of arguments for 'srem' command

The same thing happens when we call the command without any arguments:

SREM

Result:

(error) ERR wrong number of arguments for 'srem' command