0
0
RedisHow-ToBeginner · 3 min read

How to Use SPOP Command in Redis: Syntax and Examples

Use the SPOP command in Redis to remove and return one or more random members from a set. The syntax is SPOP key [count], where key is the set name and count is optional to specify how many members to pop.
📐

Syntax

The SPOP command removes and returns random members from a set stored at the given key. If you provide a count, it removes and returns that many members; otherwise, it returns one member.

  • key: The name of the set from which to pop members.
  • count (optional): Number of random members to remove and return.
redis
SPOP key [count]
💻

Example

This example shows how to add members to a set and then use SPOP to remove random members.

redis
127.0.0.1:6379> SADD fruits apple banana cherry date
(integer) 4
127.0.0.1:6379> SPOP fruits
"banana"
127.0.0.1:6379> SPOP fruits 2
1) "date"
2) "apple"
127.0.0.1:6379> SMEMBERS fruits
1) "cherry"
Output
"banana" 1) "date" 2) "apple" 1) "cherry"
⚠️

Common Pitfalls

Common mistakes when using SPOP include:

  • Using SPOP on a key that does not exist returns null or an empty array, which might be unexpected.
  • Requesting a count larger than the set size returns all members and empties the set.
  • Confusing SPOP with SRANDMEMBER, which returns random members without removing them.
redis
Wrong usage:
127.0.0.1:6379> SPOP unknownset
(nil)

Right usage:
127.0.0.1:6379> SPOP fruits 10
1) "cherry"
Output
(nil) 1) "cherry"
📊

Quick Reference

CommandDescriptionExample
SPOP keyRemove and return one random member from setSPOP fruits
SPOP key countRemove and return count random membersSPOP fruits 3
SRANDMEMBER keyReturn random member without removingSRANDMEMBER fruits

Key Takeaways

SPOP removes and returns random members from a Redis set.
You can specify how many members to pop with an optional count.
If count exceeds set size, all members are returned and set is emptied.
Using SPOP on a non-existing key returns null or empty result.
SPOP differs from SRANDMEMBER which does not remove members.