0
0
RedisHow-ToBeginner · 3 min read

How to Use INCRBY Command in Redis: Syntax and Examples

Use the INCRBY command in Redis to increase the integer value stored at a key by a specified amount. If the key does not exist, it is set to 0 before incrementing. The command returns the new value after incrementing.
📐

Syntax

The INCRBY command syntax is simple:

  • INCRBY key increment

Here, key is the name of the key holding the integer value, and increment is the integer amount to add to the current value.

If the key does not exist, Redis treats its value as 0 before adding the increment.

redis
INCRBY mycounter 5
Output
(integer) 5
💻

Example

This example shows how to use INCRBY to increase a counter by 10, then by 3:

redis
127.0.0.1:6379> SET mycounter 0
OK
127.0.0.1:6379> INCRBY mycounter 10
(integer) 10
127.0.0.1:6379> INCRBY mycounter 3
(integer) 13
Output
(integer) 10 (integer) 13
⚠️

Common Pitfalls

Common mistakes when using INCRBY include:

  • Trying to increment a key holding a non-integer value causes an error.
  • Using a non-integer increment value will also cause an error.
  • Assuming INCRBY works on keys with string or float values (it only works on integers).

Always ensure the key holds an integer or does not exist before using INCRBY.

redis
127.0.0.1:6379> SET mykey "hello"
OK
127.0.0.1:6379> INCRBY mykey 1
(error) ERR value is not an integer or out of range

-- Correct usage:
127.0.0.1:6379> SET mykey 5
OK
127.0.0.1:6379> INCRBY mykey 1
(integer) 6
Output
(error) ERR value is not an integer or out of range (integer) 6
📊

Quick Reference

CommandDescriptionExampleOutput
INCRBY key incrementIncrements integer value at key by incrementINCRBY mycounter 4(integer) new_value
Key missingIf key does not exist, it is set to 0 before incrementINCRBY newkey 2(integer) 2
Non-integer valueCauses error if key holds non-integerINCRBY mykey 1ERR value is not an integer or out of range

Key Takeaways

INCRBY increments the integer value stored at a key by a specified integer.
If the key does not exist, Redis treats its value as 0 before incrementing.
INCRBY only works on keys holding integer values; non-integer values cause errors.
Always use integer increments; non-integer increments will cause errors.
Check the key's value type before using INCRBY to avoid runtime errors.