In Redis, the DECR
command decrements the value of a specified key by one.
If the key doesn’t exist, DECR
creates the key with a value of 0
and then decrements it by one.
An error occurs if the key contains a value of the wrong type or contains a string that cannot be represented as integer.
Syntax
DECR key
Where key
is the key to decrement.
Example
Suppose we set a key like this:
SET countdown "20"
Result:
OK
Let’s quickly take a look at it:
GET countdown
Result:
"20"
OK, now let’s decrement it by one:
DECR countdown
Result:
(integer) 19
We get an integer reply with the value of the key after the DECR
operation was performed.
Let’s run the GET
command again:
GET countdown
Result:
"19"
As expected, the original value has decreased by one.
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 decrement negative values just as we can decrement positive values.
Set a negative value:
SET points "-7"
Result:
OK
Let’s quickly take a look at it:
GET points
Result:
"-7"
OK, now let’s decrement it by one:
DECR points
Result:
(integer) -8
The value has been decremented by one.
We can check this at any time by running the GET
command again:
GET points
Result:
"-8"
When the Key Doesn’t Exist
If the key doesn’t exist, DECR
creates the key with a value of 0
and then decrements it by one.
Let’s delete our score
key:
DEL points
Result:
(integer) 1
The DEL
command returns the number of keys that were deleted – in this case 1.
Now let’s try to decrement that (non-existent) key:
DECR points
Result:
(integer) -1
So we can see that the points
key has been recreated and decremented to a value of -1.
Let’s check its value:
GET points
Result:
"-1"
When the Value is the Wrong Type
As mentioned, an error occurs if the key contains a value of the wrong type or contains a string that cannot be represented as integer.
To test this, let’s try decrementing a value that can’t be represented as an integer.
Set the amount:
SET countdown "Twenty"
Result:
OK
Let’s quickly take a look at it:
GET countdown
Result:
"Twenty"
OK, now let’s try to decrement it by one:
DECR countdown
Result:
(error) ERR value is not an integer or out of range
An error occurred as expected.