The Redis SETNX
command sets a key to a given value, but only if the key doesn’t already exist. If the key already holds a value, no operation is performed.
Note: The SET
command can do the same thing, and it’s possible that the SETNX
command may be deprecated at some point. Therefore, it’s probably a good idea to use SET
instead of SETNX
if possible.
Syntax
The syntax for SETNX
goes like this:
SETNX key value
Where key
is the key to set, and value
is the value to set.
It’s basically the same as doing this:
SET key value NX
Example
Here’s a simple example to demonstrate:
SETNX lunch "Pizza"
Result:
(integer) 1
The value was set because the key didn’t already exist. In this case, the return value is an integer reply of 1
.
When the Key Already Exists
Here’s what happens when the key already exists:
SETNX lunch "Greek Salad"
Result:
(integer) 0
This time the value wasn’t set and we got an integer reply of 0
.
Just to be sure, let’s check the value of the lunch
key:
GET lunch
Result:
"Pizza"
It’s value is still the same that we assigned in the first example.