Redis ZINCRBY Command Explained

In Redis, the ZINCRBY command increments the score of a given member in a sorted set.

Syntax

The syntax goes like this:

ZINCRBY key increment member

Example

Suppose we create a sorted set like this:

ZADD cats 0 meow 0 fluffy

I added two members to this set and gave both of them the same score.

Now let’s use the ZINCRBY command to increment the score of one of those members:

ZINCRBY cats 5 meow

Result:

"5"

The command returns the new score of the member. This is a double precision floating point number represented as a string.

When the Member Doesn’t Exist

If the member doesn’t exist in the key, it’s created and incremented by the specified amount, as if its original score was 0.0:

ZINCRBY cats 7 scratch

Result:

"7"

When the Key Doesn’t Exist

If the key doesn’t exist, it’s created and the member is added and incremented as if its original score was 0.0:

ZINCRBY dogs 25 bark

Result:

"25"

Decrement the Score

We can provide a negative value in order to decrement a member’s score:

ZINCRBY dogs -3 bark

Result:

"22"

This is the same member that we added in the previous example. Here we decremented its score from 25 to 22.

Wrong Data Type

If the key exists, but it doesn’t contain a sorted set, we get an error:

ZINCRBY country 3 Australia

Result:

(error) WRONGTYPE Operation against a key holding the wrong kind of value

In this case, the country key contains a string and so we got an error.

I get the same error when I run the code against a non-sorted set:

ZINCRBY countries 3 Australia

Result:

(error) WRONGTYPE Operation against a key holding the wrong kind of value