Skip to main content
0 reactions

How to Set a Key Only If It Does Not Exist in Valkey (SET NX)

Featured image for How to Set a Key Only If It Does Not Exist in Valkey, showing SET username:ana with NX replying OK, then nil, and GET returning user-1.
Valkey SET NX.

SET with NX saves a value only if its key doesn’t exist yet. It’s how you claim something once, such as a username, without overwriting a claim that’s already there. This guide claims the username ana in Valkey®.

Type the commands at the valkey-cli prompt. To open it, run valkey-cli in a terminal.

Note: Every command and output on this page is real, run on Valkey 9.2 on an Apple silicon Mac with macOS 26.

Syntax

SyntaxPlain text
SET key value NX
  • key: the name to claim.
  • value: what to save under it.
  • NX: write only if the key doesn’t exist.

From the SET documentation (opens in a new tab).

Step 1: Claim the Name

127.0.0.1:6379>Plain text
SET username:ana "user-1" NX
OutputPlain text
OK

OK: the key didn’t exist, so Valkey saved it.

Step 2: Try to Claim It Again

127.0.0.1:6379>Plain text
SET username:ana "user-2" NX
OutputPlain text
(nil)

(nil): the name is taken, so nothing was written, and the first value stays:

127.0.0.1:6379>Plain text
GET username:ana
OutputPlain text
"user-1"
valkey-cli session where SET username:ana with NX replies OK the first time and nil the second time, and GET returns user-1.
The first claim wins: the second SET NX writes nothing.

Clean Up

127.0.0.1:6379>Plain text
DEL username:ana
OutputPlain text
(integer) 1

Common Mistakes

MistakeWhat happensDo this instead
Checking with EXISTS first, then saving with SETAnother client can create the key between the two commandsUse SET … NX, which checks and saves in one step
Reading (nil) as an errorYour app reports a failureTreat (nil) as “already taken”

FAQ

What about the SETNX command?

SETNX key value does the same job. The SET documentation (opens in a new tab) says SET’s options can replace it and that it may be removed in a future version, so use SET … NX.

Can SET NX also set an expiry?

Yes: add EX and a number of seconds, as in SET key value NX EX 60. The SET documentation uses this for a simple lock.

Conclusion

SET key value NX saves only when the key is free and replies (nil) when it isn’t, so the first claim always wins.

Additional Resources

Valkey® is a registered trademark of LF Projects, LLC. Redis® is a registered trademark of Redis Ltd. Any rights therein are reserved to Redis Ltd. Other names mentioned are trademarks of their respective owners. JD Bots isn’t affiliated with the Valkey project, LF Projects or Redis Ltd., and isn’t endorsed, supported or certified by them.

0 comments