DECR
The DECR
command in DiceDB is used to decrement the integer value of a key by one. If the key does not exist, it is set to 0 before performing the decrement operation. This command is useful for counters and other numerical operations where you need to decrease the value stored at a specific key.
Syntax
Parameters
Parameter | Description | Type | Required |
---|---|---|---|
key | The key whose value you want to decrement. This key must hold a string that can be represented as an integer. | String | Yes |
Return Value
Condition | Return Value |
---|---|
Command is successful | Integer : The new value of the key after the decrement operation. |
Syntax or specified constraints are invalid | error |
Behaviour
When the DECR
command is executed, the following steps occur:
- If the specified key doesn’t exist, it is created, with -1 as it’s value, and same is returned.
- If the specified key exists with an integer value, value is decremented and new value is returned.
- If the specified key exists with a non-integer OR out-of-range value, error message is returned as:
(error) ERR value is not an integer or out of range
Errors
The DECR
command can raise errors in the following scenarios:
Wrong Type Error
: If the key exists but the value is not a string that can be represented as an integer, DiceDB will return an error.Error Message
:(error) ERR value is not an integer or out of range
Out of Range Error
: If the value of the key is out of the range of a 64-bit signed integer after the decrement operation, DiceDB will return an error.Error Message
:(error) ERR increment or decrement would overflow
Example Usage
Basic Usage
Explanation
:
- The
SET
command initializes the keymycounter
with the value10
. - The
DECR
command decrements the value ofmycounter
by 1, resulting in9
.
Key Does Not Exist
Explanation
:
- The key
newcounter
does not exist. - DiceDB sets
newcounter
to0
and then decrements it by 1, resulting in-1
.
Error Scenario: Non-Integer Value
Explanation
:
- The
SET
command initializes the keymystring
with the value"hello"
. - The
DECR
command attempts to decrement the value ofmystring
, but since it is not an integer, an error is raised.
Error Scenario: Out of Range
Explanation
:
- The
SET
command initializes the keymycounter
with the out-of-range value for a 64-bit signed integer. - The
DECR
command attempts to decrement the value ofmycounter
, but this would result in an overflow, so an error is raised.
Alternatives
You can also use the DECRBY
command to decrement the value of a key by a specified amount.