0
0
RedisHow-ToBeginner · 3 min read

How to Use ZREM in Redis: Remove Members from Sorted Sets

Use the ZREM command in Redis to remove one or more members from a sorted set. It takes the key of the sorted set and the members to remove, returning the number of members actually removed.
📐

Syntax

The ZREM command syntax is simple:

  • ZREM key member [member ...]

Here, key is the name of the sorted set, and member is one or more members you want to remove from that set.

redis
ZREM mysortedset member1 member2
💻

Example

This example shows how to add members to a sorted set and then remove some using ZREM. It demonstrates the command's effect and output.

redis
127.0.0.1:6379> ZADD mysortedset 1 one 2 two 3 three
(integer) 3
127.0.0.1:6379> ZREM mysortedset two three
(integer) 2
127.0.0.1:6379> ZRANGE mysortedset 0 -1 WITHSCORES
1) "one"
2) "1"
Output
3 2 1) "one" 2) "1"
⚠️

Common Pitfalls

Common mistakes when using ZREM include:

  • Trying to remove members that do not exist, which returns 0 but does not cause an error.
  • Using the wrong key type (not a sorted set), which causes an error.
  • Passing no members to remove, which is invalid syntax.

Always ensure the key is a sorted set and specify at least one member to remove.

redis
127.0.0.1:6379> ZREM mysortedset
(error) ERR wrong number of arguments for 'zrem' command

# Correct usage:
127.0.0.1:6379> ZREM mysortedset one
(integer) 1
Output
(error) ERR wrong number of arguments for 'zrem' command (integer) 1
📊

Quick Reference

CommandDescriptionReturn Value
ZREM key member [member ...]Removes specified members from the sorted set stored at keyNumber of members removed
ZADD key score memberAdds members with scores to a sorted setNumber of new elements added
ZRANGE key start stopReturns members in a range by rankList of members
ZRANGE key start stop WITHSCORESReturns members and their scoresList of members and scores

Key Takeaways

Use ZREM to remove one or more members from a Redis sorted set by specifying the key and members.
ZREM returns the count of members actually removed, which can be zero if members do not exist.
Ensure the key is a sorted set; otherwise, Redis will return an error.
Always provide at least one member to remove; omitting members causes a syntax error.
ZREM does not affect the scores of other members in the sorted set.