Although the operation applies to integer values, Redis does not have a specific integer data type. Hence the value to be incremented is a string type that can be represented as a base-10 64 bit signed integer value.
Let us discuss how we can use this command.
Basic Usage
The command’s syntax can be expressed as:
The command accepts the key as the argument and returns the new value after the increment operation.
For example, start by creating a key as shown:
OK
Next, run the INCR command on the “age” key.
(integer) 24
The command returns the value of age after incrementing by one.
It is good to keep in mind that the command modifies the value of the key in place. Hence, the value of the key is the one after the increment operation.
For example:
"24"
DECR Command
If you have a command to increment a value by one, there must be a command to decrement by one, right? Yes. You are right.
Redis also provides you with the DECR command to decrement a value by one. It works very similarly to the INCR command because it takes a key holding an integer value and returns the value after decrement.
The syntax can be expressed as:
Let us look at a simple example:
Start by creating a simple key as:
OK
Next, decrement the value using the DECR command:
(integer) 999
As we mentioned, the INCR and DECR command work on an integer value. Redis returns an error as shown below if you use the commands on a non-integer value.
127.0.0.1:6379> INCR nonInt
(error) ERR value is not an integer or out of range
INCRBY/DECRBY Commands
Suppose you want to increment a value by a specific integer value. For example, if you’re going to increase a value by 5 using the INCR command, you have to re-run the command five times.
To resolve this, you can use the INCRBY and DECRBY commands to increment or decrement a value by a specific factor, respectively.
The syntax is as shown:
The commands take the key and an increment value as the arguments.
For example:
127.0.0.1:6379> INCRBY sample 1000
(integer) 2500
The commands will return the value after increment or decrement operations.
Closing
It is good to keep the increment and decrement commands at hand to work with Redis. Using this tutorial, you learned how the commands work and use them in a Redis database.