0
0
RedisHow-ToBeginner · 3 min read

How to Use ZINCRBY in Redis: Increment Sorted Set Scores

Use the ZINCRBY command in Redis to increase the score of a member in a sorted set by a specified amount. The syntax is ZINCRBY key increment member, which updates the member's score and returns the new score.
📐

Syntax

The ZINCRBY command increments the score of a member in a sorted set stored at a given key.

  • key: The name of the sorted set.
  • increment: The amount to add to the member's score (can be positive or negative).
  • member: The member whose score you want to increase.
redis
ZINCRBY key increment member
💻

Example

This example shows how to add a member to a sorted set and then increment its score using ZINCRBY.

redis
127.0.0.1:6379> ZADD leaderboard 10 "Alice"
(integer) 1
127.0.0.1:6379> ZINCRBY leaderboard 5 "Alice"
"15"
127.0.0.1:6379> ZRANGE leaderboard 0 -1 WITHSCORES
1) "Alice"
2) "15"
Output
1) "Alice" 2) "15"
⚠️

Common Pitfalls

Common mistakes when using ZINCRBY include:

  • Using a key that does not hold a sorted set, which causes an error.
  • Passing a non-numeric increment value, which is invalid.
  • Expecting ZINCRBY to add a new member without specifying the increment correctly.

Always ensure the key is a sorted set and the increment is a valid number.

redis
127.0.0.1:6379> SET mykey "value"
OK
127.0.0.1:6379> ZINCRBY mykey 1 "member"
(error) WRONGTYPE Operation against a key holding the wrong kind of value

-- Correct usage --
127.0.0.1:6379> ZADD myset 1 "member"
(integer) 1
127.0.0.1:6379> ZINCRBY myset 2 "member"
"3"
Output
(error) WRONGTYPE Operation against a key holding the wrong kind of value "3"
📊

Quick Reference

CommandDescriptionExample
ZINCRBY key increment memberIncrement member's score in sorted setZINCRBY leaderboard 5 "Alice"
ZADD key score memberAdd member with score to sorted setZADD leaderboard 10 "Alice"
ZRANGE key start stop WITHSCORESGet members with scoresZRANGE leaderboard 0 -1 WITHSCORES

Key Takeaways

ZINCRBY increments the score of a member in a sorted set by a given number.
The command returns the new score of the member after incrementing.
Ensure the key is a sorted set to avoid errors.
The increment must be a valid numeric value, positive or negative.
Use ZADD to add members before incrementing if they don't exist.