How to Use DECR Command in Redis: Syntax and Examples
Use the
DECR command in Redis to decrease the integer value stored at a key by one. If the key does not exist, it is set to 0 before decrementing, resulting in -1. The command returns the new value after decrement.Syntax
The DECR command syntax is simple and requires only the key name as an argument.
- DECR key: Decreases the integer value of
keyby 1.
If the key does not exist, Redis treats it as 0 before decrementing. The key must hold a string representing an integer, or an error will occur.
redis
DECR key
Example
This example shows how to use DECR to decrease a counter stored in Redis.
redis
SET counter 10
DECR counter
GET counterOutput
OK
(integer) 9
"9"
Common Pitfalls
Common mistakes when using DECR include:
- Trying to decrement a key holding a non-integer value, which causes an error.
- Assuming
DECRworks on keys that hold data types other than strings. - Not handling the case when the key does not exist, which sets it to -1 after decrement.
redis
SET name "hello" DECR name # Correct usage: SET visits 5 DECR visits
Output
(error) ERR value is not an integer or out of range
OK
(integer) 4
Quick Reference
| Command | Description | Returns |
|---|---|---|
| DECR key | Decreases integer value of key by 1 | New integer value after decrement |
| If key missing | Key is set to 0 before decrement | -1 |
| Error case | Key holds non-integer value | Error |
Key Takeaways
DECR decreases the integer value stored at a key by one and returns the new value.
If the key does not exist, DECR sets it to -1 after decrementing from 0.
The key must hold a string representing an integer; otherwise, DECR returns an error.
DECR only works on string keys storing integers, not other data types.
Use GET after DECR to verify the updated value.