0
0
Redisquery~5 mins

SETNX for set-if-not-exists in Redis

Choose your learning style9 modes available
Introduction
SETNX helps you add a value only if the key is not already there. It stops overwriting existing data by mistake.
When you want to create a lock to prevent others from changing data at the same time.
When you want to set a default value only if no value exists yet.
When you want to ensure a key is created once and not changed later.
When you want to avoid overwriting important data accidentally.
When you want to check if a key exists and set it in one step.
Syntax
Redis
SETNX key value
SETNX means 'SET if Not eXists'.
It returns 1 if the key was set, 0 if the key already exists.
Examples
Sets the key 'user:123' to 'John' only if 'user:123' does not exist.
Redis
SETNX user:123 "John"
Creates a session token only if it is not already set.
Redis
SETNX session:token "abc123"
Sets the config mode to 'production' only if it is not set yet.
Redis
SETNX config:mode "production"
Sample Program
First, we try to set 'lock:key' to 'locked'. Then we get its value. Next, we try to set it again to 'newlock' but it won't change because the key exists. Finally, we get the value again to see it did not change.
Redis
SETNX lock:key "locked"
GET lock:key
SETNX lock:key "newlock"
GET lock:key
OutputSuccess
Important Notes
SETNX is atomic, so it is safe to use in concurrent environments.
If you want to set a key with expiration only if it does not exist, consider using SET with NX and EX options in newer Redis versions.
Remember SETNX only sets the key if it does not exist; it does not update existing keys.
Summary
SETNX sets a key only if it does not exist.
It returns 1 if the key was set, 0 if it was already there.
Useful for locks, defaults, and avoiding overwrites.