Redis INCR Command Explained

In Redis, the INCR command increments the value of a specified key by one.

If the key doesn’t exist, INCR creates the key with a value of 0 and then increments it by one.

An error occurs if the key contains a value of the wrong type or contains a string that cannot be represented as integer. 

Syntax

INCR key

Where key is the key to increment.

Example

Suppose we set a key like this:

SET pageviews "20"

Result:

OK

Let’s quickly take a look at it:

GET pageviews

Result:

"20"

OK, now let’s increment it by one:

INCR pageviews

Result:

(integer) 21

We get an integer reply with the value of the key after the INCR operation was performed.

Let’s run the GET command again:

GET pageviews

Result:

"21"

As expected, the original value has been incremented by one.

Negative Values

Redis does not have a dedicated integer type. However, the string stored at the key is interpreted as a base-10 64 bit signed integer to execute the operation. Therefore, we can increment negative values just as we can increment positive values.

Set a negative value:

SET points "-7"

Result:

OK

Let’s quickly take a look at it:

GET points

Result:

"-7"

OK, now let’s increment it by one:

INCR points

Result:

(integer) -6

The value has been incremented by one.

We can check this at any time by running the GET command again:

GET points

Result:

"-6"

When the Key Doesn’t Exist

If the key doesn’t exist, INCR creates the key with a value of 0 and then increments it by one.

Let’s delete our score key:

DEL points

Result:

(integer) 1

The DEL command returns the number of keys that were deleted – in this case 1.

Now let’s try to increment that (non-existent) key:

INCR points

Result:

(integer) 1

So we can see that the points key has been recreated with a value of 1.

When the Value is the Wrong Type

As mentioned, an error occurs if the key contains a value of the wrong type or contains a string that cannot be represented as integer.

To test this, let’s try incrementing a value that can’t be represented as an integer.

Set the amount:

SET pageviews "Twenty"

Result:

OK

Let’s quickly take a look at it:

GET pageviews

Result:

"Twenty"

OK, now let’s try to increment it by one:

INCR pageviews

Result:

(error) ERR value is not an integer or out of range

An error occurred as expected.