0
0
Redisquery~5 mins

INCRBY and DECRBY in Redis

Choose your learning style9 modes available
Introduction

INCRBY and DECRBY help you add or subtract numbers stored in Redis keys easily.

When you want to count how many times something happens, like page views.
When you need to increase or decrease a user's score in a game.
When tracking inventory changes, like adding or removing items.
When you want to update a numeric value without reading it first.
When you want a fast way to change numbers in a shared database.
Syntax
Redis
INCRBY key increment
DECRBY key decrement

key is the name of the stored number.

increment and decrement are integers.

Examples
Adds 5 to the number stored in 'visits'.
Redis
INCRBY visits 5
Subtracts 3 from the number stored in 'stock'.
Redis
DECRBY stock 3
Increases 'score' by 10 points.
Redis
INCRBY score 10
Decreases 'balance' by 2 units.
Redis
DECRBY balance 2
Sample Program

This sets 'counter' to 10, adds 7, subtracts 3, then gets the final value.

Redis
SET counter 10
INCRBY counter 7
DECRBY counter 3
GET counter
OutputSuccess
Important Notes

If the key does not exist, INCRBY and DECRBY start it at 0 before changing.

These commands only work on keys holding integer values.

Using these commands is faster than getting the value, changing it in your app, then setting it back.

Summary

INCRBY adds a number to a Redis key's value.

DECRBY subtracts a number from a Redis key's value.

They are simple and fast ways to update numbers in Redis.