0
0
Redisquery~10 mins

SETNX for set-if-not-exists in Redis - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - SETNX for set-if-not-exists
Receive SETNX command
Check if key exists?
YesReturn 0 (no set)
No
Set key with value
Return 1 (set successful)
The SETNX command checks if a key exists. If not, it sets the key with a value and returns 1. If the key exists, it does nothing and returns 0.
Execution Sample
Redis
SETNX mykey "Hello"
SETNX mykey "World"
GET mykey
Try to set 'mykey' to 'Hello' if it doesn't exist, then try to set it to 'World' again, then get the value of 'mykey'.
Execution Table
StepCommandKey Exists?ActionReturn ValueKey Value After
1SETNX mykey "Hello"NoSet key 'mykey' to 'Hello'1"Hello"
2SETNX mykey "World"YesDo not set, key exists0"Hello"
3GET mykeyYesReturn value of 'mykey'"Hello""Hello"
💡 After step 3, the key 'mykey' holds 'Hello' because the second SETNX did not overwrite it.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3
mykeydoes not exist"Hello""Hello""Hello"
Return ValueN/A10"Hello"
Key Moments - 2 Insights
Why does the second SETNX command not change the value of 'mykey'?
Because SETNX only sets the key if it does not exist. In step 2 of the execution_table, the key 'mykey' already exists, so the command returns 0 and does not overwrite the value.
What does the return value 1 or 0 from SETNX mean?
Return value 1 means the key was set because it did not exist (step 1). Return value 0 means the key was not set because it already existed (step 2).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the return value of the first SETNX command?
A"Hello"
B0
C1
Dnull
💡 Hint
Check the 'Return Value' column in row 1 of the execution_table.
At which step does the key 'mykey' get its value set for the first time?
AStep 3
BStep 1
CStep 2
DBefore Step 1
💡 Hint
Look at the 'Action' and 'Key Value After' columns in the execution_table.
If the key 'mykey' did not exist before step 2, what would the return value of the second SETNX be?
A1
B0
C"Hello"
Dnull
💡 Hint
Recall that SETNX returns 1 if the key does not exist and sets it.
Concept Snapshot
SETNX key value
- Sets key to value only if key does not exist
- Returns 1 if key was set
- Returns 0 if key already exists
- Does not overwrite existing keys
Useful for atomic 'set-if-not-exists' operations
Full Transcript
The SETNX command in Redis checks if a key exists. If the key does not exist, it sets the key with the given value and returns 1. If the key already exists, it does nothing and returns 0. For example, if you run SETNX mykey "Hello" when 'mykey' does not exist, it sets 'mykey' to "Hello" and returns 1. If you run SETNX mykey "World" again, it returns 0 and does not change the value. Finally, GET mykey returns "Hello". This command is useful when you want to set a value only if it is not already set, avoiding overwriting existing data.