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
SPOPon a key that does not exist returnsnullor an empty array, which might be unexpected. - Requesting a
countlarger than the set size returns all members and empties the set. - Confusing
SPOPwithSRANDMEMBER, 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
| Command | Description | Example |
|---|---|---|
| SPOP key | Remove and return one random member from set | SPOP fruits |
| SPOP key count | Remove and return count random members | SPOP fruits 3 |
| SRANDMEMBER key | Return random member without removing | SRANDMEMBER 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.