How to Use INCR Command in Redis: Simple Guide
Use the
INCR command in Redis to increase the integer value stored at a key by one. If the key does not exist, INCR sets it to 1. This command only works on keys holding integer values stored as strings.Syntax
The INCR command syntax is simple and takes one argument:
key: The name of the key whose integer value you want to increment.
If the key does not exist, Redis creates it with the value 1. If the key contains a value that is not an integer, Redis returns an error.
redis
INCR key
Example
This example shows how to increment a counter stored in Redis using the INCR command. It demonstrates incrementing an existing key and creating a new key if it does not exist.
redis
127.0.0.1:6379> SET page_views 10 OK 127.0.0.1:6379> INCR page_views (integer) 11 127.0.0.1:6379> INCR new_counter (integer) 1
Output
(integer) 11
(integer) 1
Common Pitfalls
Common mistakes when using INCR include:
- Trying to increment a key holding a non-integer value, which causes an error.
- Assuming
INCRworks on keys with string values that are not integers. - Not handling the case where the key does not exist (though Redis sets it to 1 automatically).
Example of wrong and right usage:
redis
127.0.0.1:6379> SET name "Alice" OK 127.0.0.1:6379> INCR name (error) ERR value is not an integer or out of range # Correct usage: 127.0.0.1:6379> SET visits 5 OK 127.0.0.1:6379> INCR visits (integer) 6
Output
(error) ERR value is not an integer or out of range
(integer) 6
Quick Reference
| Command | Description |
|---|---|
| INCR key | Increment the integer value of key by one |
| INCRBY key increment | Increment the integer value of key by a specified amount |
| SET key value | Set the string value of a key |
| GET key | Get the value of a key |
Key Takeaways
Use INCR to increase an integer stored at a key by one in Redis.
INCR creates the key with value 1 if it does not exist.
INCR only works on keys holding integer values stored as strings.
Trying to INCR a non-integer value causes an error.
Use INCRBY to increment by values other than one.