0
0
Redisquery~5 mins

INCR and DECR for counters in Redis

Choose your learning style9 modes available
Introduction

INCR and DECR help you easily add or subtract 1 from a number stored in Redis. This is useful for counting things quickly.

Counting how many times a button is clicked on a website.
Tracking the number of users currently online.
Keeping score in a game.
Counting how many times a product is viewed.
Managing inventory stock levels by increasing or decreasing counts.
Syntax
Redis
INCR key
DECR key

INCR increases the number stored at key by 1.

DECR decreases the number stored at key by 1.

Examples
This adds 1 to the number stored in page_views.
Redis
INCR page_views
This subtracts 1 from the number stored in stock_item_123.
Redis
DECR stock_item_123
Increase the count of users by 1.
Redis
INCR user_count
Decrease the count of users by 1.
Redis
DECR user_count
Sample Program

Start the counter at 10, then increase, decrease, and increase it again. Finally, get the current value.

Redis
SET counter 10
INCR counter
DECR counter
INCR counter
GET counter
OutputSuccess
Important Notes

If the key does not exist, INCR and DECR will create it with a starting value of 0 before changing it.

These commands only work on keys holding integer values.

Using INCR or DECR on a key with a non-integer value will cause an error.

Summary

INCR and DECR are simple commands to add or subtract 1 from a number in Redis.

They are useful for counting things like clicks, users, or stock.

If the key is missing, Redis starts it at 0 automatically.