How to Use SETNX Command in Redis for Conditional Key Setting
Use the
SETNX command in Redis to set a key to a value only if the key does not already exist. It returns 1 if the key was set, and 0 if the key already exists, preventing overwriting.Syntax
The SETNX command syntax is simple:
SETNX key value
Here, key is the name of the key you want to set, and value is the value you want to assign to that key.
The command sets the key only if it does not already exist.
redis
SETNX mykey "Hello"Example
This example shows how SETNX works by trying to set a key twice. The first time it sets the key successfully, returning 1. The second time, since the key exists, it returns 0 and does not overwrite the value.
redis
127.0.0.1:6379> SETNX mykey "Hello" (integer) 1 127.0.0.1:6379> SETNX mykey "World" (integer) 0 127.0.0.1:6379> GET mykey "Hello"
Output
(integer) 1
(integer) 0
"Hello"
Common Pitfalls
Common mistakes when using SETNX include:
- Expecting
SETNXto overwrite existing keys. It never overwrites; it only sets if the key is missing. - Not checking the return value, which indicates success (
1) or failure (0). - Using
SETNXwithout expiration, which can cause stale keys to persist indefinitely.
To set a key only if it does not exist and also set an expiration, use SET key value NX EX seconds instead (available in Redis 2.6.12+).
redis
127.0.0.1:6379> SETNX mykey "Hello" (integer) 1 127.0.0.1:6379> SETNX mykey "World" (integer) 0 # Correct way to set with expiration: 127.0.0.1:6379> SET mykey "Hello" NX EX 10 OK
Output
(integer) 1
(integer) 0
OK
Quick Reference
| Command | Description | Return Value |
|---|---|---|
| SETNX key value | Set key to value if key does not exist | 1 if set, 0 if key exists |
| GET key | Get the value of key | Value or nil if key does not exist |
| SET key value NX EX seconds | Set key with value if not exists and expire after seconds | OK if set, nil if not |
Key Takeaways
SETNX sets a key only if it does not already exist, returning 1 on success and 0 if the key exists.
Always check the return value of SETNX to know if the key was set.
SETNX does not support expiration; use SET with NX and EX options to set keys conditionally with expiry.
SETNX never overwrites existing keys, so it is useful for locking or initialization.
For atomic conditional set with expiration, prefer the modern SET command with NX and EX flags.