Bird
Raised Fist0
Redisquery~10 mins

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

Choose your learning style10 modes available
Concept Flow - SETNX for set-if-not-exists
Receive SETNX command
↓
Check if key exists?
Yes→Return 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.

Practice

(1/5)
1. What does the Redis command SETNX do?
easy
A. Sets a key only if it does not already exist
B. Always sets a key, overwriting any existing value
C. Deletes a key if it exists
D. Returns the value of a key without changing it

Solution

  1. Step 1: Understand the purpose of SETNX

    SETNX stands for 'SET if Not eXists'. It sets a key only if the key does not already exist in Redis.
  2. Step 2: Compare with other commands

    Unlike SET, which always sets the key, SETNX avoids overwriting existing keys.
  3. Final Answer:

    Sets a key only if it does not already exist -> Option A
  4. Quick Check:

    SETNX = set-if-not-exists [OK]
Hint: Remember NX means 'Not eXists' for setting keys [OK]
Common Mistakes:
  • Thinking SETNX always overwrites keys
  • Confusing SETNX with GET command
  • Assuming SETNX deletes keys
2. Which of the following is the correct syntax to set key 'user:1' to 'Alice' only if it does not exist using SETNX?
easy
A. SETNX user:1 Alice
B. SET user:1 Alice NX
C. SETNX 'user:1' 'Alice'
D. SET user:1 Alice XX

Solution

  1. Step 1: Recall SETNX syntax

    The correct syntax is SETNX key value without quotes unless the key or value contains spaces.
  2. Step 2: Analyze options

    SETNX user:1 Alice uses correct syntax without quotes, which is valid. SETNX 'user:1' 'Alice' uses quotes which are not required in Redis CLI and may cause errors.
  3. Final Answer:

    SETNX user:1 Alice -> Option A
  4. Quick Check:

    SETNX key value is correct syntax [OK]
Hint: Use SETNX key value without quotes for simple keys [OK]
Common Mistakes:
  • Using SET with NX option incorrectly
  • Adding quotes unnecessarily in Redis CLI
  • Using XX option which means 'only set if exists'
3. Given the following Redis commands executed in order:
SETNX lock 1
SETNX lock 2
What will be the result of the second SETNX command?
medium
A. 1
B. 2
C. 0
D. Error

Solution

  1. Step 1: Execute first SETNX

    The first command SETNX lock 1 sets the key 'lock' to '1' because it does not exist yet. It returns 1 indicating success.
  2. Step 2: Execute second SETNX

    The second command SETNX lock 2 tries to set 'lock' again, but since 'lock' already exists, it does not overwrite and returns 0.
  3. Final Answer:

    0 -> Option C
  4. Quick Check:

    SETNX returns 0 if key exists [OK]
Hint: SETNX returns 0 if key already exists [OK]
Common Mistakes:
  • Assuming SETNX overwrites existing keys
  • Expecting the second SETNX to return 1
  • Confusing return values with stored values
4. You run the command SETNX mykey without a value. What is the expected result?
medium
A. Returns 1 and sets mykey to NULL
B. Syntax error due to missing value
C. Sets mykey to an empty string
D. Returns 0 because key exists

Solution

  1. Step 1: Check command syntax requirements

    SETNX requires exactly two arguments: a key and a value. Omitting the value causes a syntax error.
  2. Step 2: Analyze the command given

    The command SETNX mykey has only one argument after the command name, so Redis will return a syntax error.
  3. Final Answer:

    Syntax error due to missing value -> Option B
  4. Quick Check:

    SETNX needs key and value arguments [OK]
Hint: Always provide both key and value for SETNX [OK]
Common Mistakes:
  • Trying to set key without value
  • Assuming missing value defaults to empty string
  • Expecting 0 return instead of error
5. You want to implement a simple lock using Redis SETNX. Which sequence correctly acquires the lock and handles the case when the lock is already held?
hard
A. Use DEL lock before SETNX to ensure lock is free
B. Use SET lock 1 NX; if returns OK, lock acquired; else delete lock
C. Use SETNX lock 1; if returns 0, overwrite lock with SET
D. Use SETNX lock 1; if returns 1, lock acquired; else wait and retry

Solution

  1. Step 1: Understand lock acquisition with SETNX

    SETNX sets the lock key only if it does not exist, returning 1 if successful, which means lock acquired.
  2. Step 2: Handle lock already held

    If SETNX returns 0, the lock exists, so the client should wait and retry later instead of overwriting or deleting the lock.
  3. Final Answer:

    Use SETNX lock 1; if returns 1, lock acquired; else wait and retry -> Option D
  4. Quick Check:

    SETNX + retry loop is standard lock pattern [OK]
Hint: SETNX returns 1 means lock acquired; else retry [OK]
Common Mistakes:
  • Overwriting lock without checking SETNX result
  • Deleting lock blindly before setting
  • Assuming SETNX returns OK instead of 1 or 0
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard