# SETNX

> Set a string value only if the key does not exist.

URL: https://docs.hotkv.com/commands/setnx/

```
SETNX key value
```

- Group: String
- Complexity: O(1)
- HotKV Cloud: all plans
- On-Premise: no license needed

`SETNX` stores `value` at `key` only when the key does not exist. It is the
same as `SET key value NX`, but replies with an integer. To set a time to live
in the same step, use [SET](https://docs.hotkv.com/commands/set/index.md) with `NX` and `EX` instead.

## Return value

| Case | RESP2 | RESP3 |
| --- | --- | --- |
| The key was set | Integer `1` | Integer `1` |
| The key already existed | Integer `0` | Integer `0` |

## Examples

```
127.0.0.1:6379> SETNX leader "node-a"
(integer) 1
127.0.0.1:6379> SETNX leader "node-b"
(integer) 0
127.0.0.1:6379> GET leader
"node-a"
```

## Compatibility

Same as Redis 7 and Valkey 8.

## See also

[SET](https://docs.hotkv.com/commands/set/index.md), [MSETNX](https://docs.hotkv.com/commands/msetnx/index.md),
[GETSET](https://docs.hotkv.com/commands/getset/index.md)