In Redis, the INCRBY
command increments the value of a key by the specified amount.
If the key doesn’t exist, INCRBY
creates the key with a value of 0
and then increments it by the specified amount.
An error occurs if the key contains a value of the wrong type or contains a string that cannot be represented as integer. INCRBY
operations are limited to 64 bit signed integers.
Syntax
INCRBY key increment
Where key
is the key to increment, and increment
is the amount to increment it by.
Example
Suppose we set a key like this:
SET score "10"
Result:
OK
Let’s quickly take a look at it:
GET score
Result:
"10"
OK, now let’s increment it by seven:
INCRBY score 7
Result:
(integer) 17
We get an integer reply with the value of the key after the INCRBY
operation was performed.
Let’s run the GET
command again:
GET score
Result:
"17"
As expected, the original value of 10 has been incremented by 7.
Negative Values
Redis does not have a dedicated integer type. However, the string stored at the key is interpreted as a base-10 64 bit signed integer to execute the operation. Therefore, we can increment negative values just as we can increment positive values.
Set a negative value:
SET score "-10"
Result:
OK
Let’s quickly take a look at it:
GET score
Result:
"-10"
OK, now let’s increment it by seven:
INCRBY score 7
Result:
(integer) -3
The value has been incremented by seven.
We can check this at any time by running the GET
command again:
GET score
Result:
"-3"
We can also increment it by a negative amount, which has the effect of decrementing the value:
INCRBY score -7
Result:
(integer) -10
We can also use the DECR
and DECRBY
commands to decrement values.
When the Key Doesn’t Exist
If the key doesn’t exist, INCRBY
creates the key with a value of 0
and then increments it by the specified amount.
Let’s delete our score
key:
DEL score
Result:
(integer) 1
The DEL
command returns the number of keys that were deleted – in this case 1.
Now let’s try to increment that (non-existent) key:
INCRBY score 10
Result:
(integer) 10
So we can see that score
has been recreated with a value of 10.
When the Value is the Wrong Type
An error occurs if the key contains a value of the wrong type or contains a string that cannot be represented as an integer.
To test this, let’s try incrementing a value that can’t be represented as an integer.
Set the amount:
SET score "Ten"
Result:
OK
Let’s quickly take a look at it:
GET score
Result:
"Ten"
OK, now let’s try to increment it by seven:
INCRBY score 7
Result:
(error) ERR value is not an integer or out of range
An error occurred as expected.
Increment by One
Although INCRBY
can be used to increment a key by one, there’s another command called INCR
that is designed to do exactly that. When using INCR
, you don’t need to specify the increment amount – you only need to specify the key.
So the following:
INCR score
Is the equivalent of this:
INCRBY score 1