Redis SPOP Command Explained

In Redis, the SPOP command removes and returns one or more random members from the set value store at the specified key.

This command is similar to the SRANDMEMBER command in that it returns one or more random members from a set, but SPOP removes it, whereas SRANDMEMBER doesn’t.

Syntax

The syntax goes like this:

SPOP key [count]

By default, only one member is returned. The optional count argument can be used to return more than one member.

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 SPOP command to remove and return a random member from that set:

SPOP animals

Result:

"Zebra"

OK, so let’s take another look at the set:

SMEMBERS animals

Result:

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

We can see that Zebra has been removed from the set.

Remove Multiple Members

As mentioned, we can pop multiple members from the set. To do this, we use an optional second argument to specify the number of members to pop:

SPOP animals 2

Result:

1) "Bird"
2) "Cow"

This time two random members were popped.

Let’s take another look at the set:

SMEMBERS animals

Result:

1) "Horse"
2) "Dog"
3) "Cat"

So, we’re now down to just three members, from our original six.

Passing Too Many Arguments

Passing the wrong number of arguments results in an error. At the time of writing, SPOP accepts up to two arguments. Any more results in an error:

SPOP animals 2 3

Result:

(error) ERR syntax error

Passing No Arguments

Calling SPOP without passing any arguments also results in an error:

SPOP

Result:

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

Exceeding the Set’s Cardinality

Passing a count argument that exceeds the set’s cardinality results in all members being popped:

SPOP animals 20

Result:

1) "Horse"
2) "Dog"
3) "Cat"

We can see that all three remaining members were popped from the set.

Now calling SMEMBERS returns an empty array:

SMEMBERS animals

Result:

(empty array)