w3resource

Redis String: SETNX key value

Redis SETNX command

Redis SETNX command is used to set some string value in redis key, if the key does not exist in redis. When key already holds a value, no operation is performed. SETNX is short for "SET if Not eXists".

Here are some common uses and scenarios for the "SETNX" command:

  • Atomic Key Creation: Safely create a new key-value pair if the key does not already exist.
  • Flags and Locks: Implement distributed locks or flags using keys that are set only once.
  • Idempotent Operations: Ensure idempotent operations by setting values conditionally.
  • Initialization: Initialize default values or configurations if they are not already set.
  • Concurrency Control: Coordinate actions across multiple clients without overwriting existing data.

Syntax:

SETNX KEY_NAME VALUE

Available since

1.0.0.

Return Value

Integer replies 1 or 0

  • 1, if the key is set.
  • 0, if the key is not set.

Return Value Type

Integer

Example: Redis SETNX

redis 127.0.0.1:6379> SETNX mykey redis
(integer) 1
redis 127.0.0.1:6379> SETNX mykey mongodb
(integer) 0
redis 127.0.0.1:6379> GET mykey
"redis"

Previous: SETEX
Next: SETRANGE



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/redis/redis-setnx-key-value.php