In Redis, we have several options for decrementing a key. By this, I mean, reducing the value of a key by one or more. For example, if we set a key to 15, we can decrement it by 1 to make 14. Or we can increment it by whatever amount we desire.
The DECR
Command
Our first option is to use the DECR
command. This command decrements the key by one. If the key doesn’t exist, it’s created with a value of 0
, then decremented by 1
.
Suppose we create the following key:
SET score 50
Result:
OK
Here’s an example of using DECR
to decrement that value by one:
DECR score
Result:
(integer) 49
This command returns the value of the key after the decrement has taken place. So if we run the same command again, we get the following:
DECR score
Result:
(integer) 48
The DECRBY
Command
Another option is to use the DECRBY
command. This command decrements the key’s value by a specified amount. If the key doesn’t exist, it’s created with a value of 0
, then decremented by the specified amount.
Here’s an example of using DECRBY
on the same key and value from the previous example:
DECRBY score 10
Result:
(integer) 38
This command returns the value of the key after the decrement has taken place. In this case the initial value was 48, and we decremented it by 10.
The INCRBY
Command
If we pass a negative value to the INCRBY
command, it has the effect of decrementing the value.
Here’s an example of using INCRBY
with a negative argument:
INCRBY score -2
Result:
(integer) 36
In this case we used -2
which decremented the value by 2.
The INCRBYFLOAT
Command
If you’re working with floating point numbers, you can use the INCRBYFLOAT
command. This command is similar to INCRBY
except that it works on floating point numbers, and also allows you to increment by a floating point number.
We can pass a negative value to this command to decrement the value:
INCRBYFLOAT score -10.45
Result:
"25.55"