# HSETNX

> Set a hash field only if it does not exist yet.

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

```
HSETNX key field value
```

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

`HSETNX` stores `value` in `field` of the hash at `key`, but only when that
field is not already present. A missing key is created. If the field exists,
nothing changes.

## Return value

| Case | RESP2 | RESP3 |
| --- | --- | --- |
| Field was set | Integer `1` | Same |
| Field already existed | Integer `0` | Same |

`HSETNX` replies with a `WRONGTYPE` error if `key` holds a value that is not a
hash.

## Examples

```
127.0.0.1:6379> HSETNX user:1 name "Ada"
(integer) 1
127.0.0.1:6379> HSETNX user:1 name "Grace"
(integer) 0
127.0.0.1:6379> HGET user:1 name
"Ada"
```

## Compatibility

Same as Redis 7.4 and Valkey 8.

## See also

[HSET](https://docs.hotkv.com/commands/hset/index.md), [HSETEX](https://docs.hotkv.com/commands/hsetex/index.md), [HEXISTS](https://docs.hotkv.com/commands/hexists/index.md),
[SETNX](https://docs.hotkv.com/commands/setnx/index.md)