Redis HINCRBY Command

The Redis HINCRBY command increments the number that’s stored at the specified field in the hash at the specified key. We specify how much we want the field to increment by when we call the command.

Syntax

The syntax goes like this:

HINCRBY key field increment

Example

Suppose we set the following hash:

HSET player username "Rob" points 20

Result:

(integer) 2

We can use HINCRBY to increment the points field in that hash:

HINCRBY player points 5

Result:

(integer) 25

The command returns an integer reply with the value of the field after the operation has taken place.

Negative Values

We can also use a negative value to decrement the field:

HINCRBY player points -5

Result:

(integer) 20

Non-Existent Fields

If the field doesn’t exist in the given hash, it’s created, set to 0, and then incremented by the specified amount:

HINCRBY player credit 18

Result:

(integer) 18

We can use a command such as HGETALL to check the new key’s field and value:

HGETALL player

Result:

1) "username"
2) "Rob"
3) "points"
4) "20"
5) "credit"
6) "18"

Non-Existent Keys

If the key doesn’t exist, it’s created with the field set to 0, and then incremented by the specified amount:

HINCRBY newkey points 5

Result:

(integer) 5

We can use a command such as HGETALL to check the new key’s field and value:

HGETALL newkey

Result:

1) "points"
2) "5"

Passing the Wrong Number of Arguments

Passing the wrong number of arguments results in an error:

HINCRBY player points 10 credit 5

Result:

(error) ERR wrong number of arguments for 'hincrby' command