0
0
Redisquery~10 mins

INCR and DECR for counters in Redis - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - INCR and DECR for counters
Start with a key holding a number
Receive INCR or DECR command
Fetch current value of key
Add 1 if INCR, subtract 1 if DECR
Store new value back to key
Return new value as result
End
The flow shows how Redis increments or decrements a numeric value stored at a key, updating and returning the new value.
Execution Sample
Redis
SET counter 5
INCR counter
DECR counter
INCR counter
This sequence sets a counter to 5, increments it, decrements it, then increments it again.
Execution Table
StepCommandCurrent ValueOperationNew ValueOutput
1SET counter 5N/ASet to 55OK
2INCR counter5+166
3DECR counter6-155
4INCR counter5+166
5END6No more commands6Execution stops
💡 No more commands to execute, final counter value is 6
Variable Tracker
VariableStartAfter 1After 2After 3Final
counterN/A5656
Key Moments - 2 Insights
Why does the counter value change after each INCR or DECR command?
Each INCR adds 1 and each DECR subtracts 1 from the current value, as shown in steps 2, 3, and 4 of the execution_table.
What happens if the key does not exist before INCR or DECR?
Redis treats a missing key as 0, so INCR sets it to 1 and DECR sets it to -1, but this example starts with SET so the key exists.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output after the first INCR command?
A6
B5
C7
DError
💡 Hint
Check row 2 in the execution_table under Output column
At which step does the counter value return to 5?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at the New Value column in execution_table row 3
If we remove the initial SET command, what would INCR counter return on the first call?
A0
BError
C1
DN/A
💡 Hint
Redis treats missing keys as 0 before incrementing, so INCR returns 1
Concept Snapshot
INCR and DECR commands in Redis:
- INCR key: increases the integer value by 1
- DECR key: decreases the integer value by 1
- If key does not exist, treated as 0 before operation
- Returns the new value after operation
- Useful for counters and simple numeric tracking
Full Transcript
This visual execution trace shows how Redis commands INCR and DECR work on a counter key. Starting with setting the counter to 5, each INCR adds 1 and each DECR subtracts 1. The execution table tracks each step's command, current value, operation, new value, and output. The variable tracker shows how the counter changes over time. Key moments clarify why values change and what happens if the key is missing. The quiz tests understanding of outputs and behavior. This helps beginners see exactly how Redis updates counters step-by-step.