# HRANDFIELD

> Return one or more random fields of a hash, optionally with their values.

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

```
HRANDFIELD key [count [WITHVALUES]]
```

- Group: Hash
- Complexity: O(N) where N is the number of fields returned
- HotKV Cloud: all plans
- On-Premise: no license needed

`HRANDFIELD` picks random fields from the hash at `key` without changing it.

- Without `count`, it returns one random field name.
- With a positive `count`, it returns up to `count` distinct fields. If the
  hash has `count` fields or fewer, you get all of them.
- With a negative `count`, it returns exactly `|count|` fields, and the same
  field can appear more than once.
- A `count` of `0` returns an empty array.

## Options

| Option | Effect |
| --- | --- |
| `count` | How many fields to return, as described above. |
| `WITHVALUES` | Return each field together with its value. Only valid after `count`. |

`count` and `WITHVALUES` are checked before the key is looked up, so a bad
argument is an error even for a missing key.

## Return value

| Case | RESP2 | RESP3 |
| --- | --- | --- |
| No `count` | Bulk string: a field name, or nil bulk string if the key does not exist | Bulk string, or null |
| With `count` | Array of field names (empty if the key does not exist) | Same |
| With `count` and `WITHVALUES` | Flat array: field, value, field, value, ... | Array of two-element arrays: `[field, value]` |

Errors:

- `ERR value is not an integer or out of range` if `count` is not an integer.
- `ERR value is out of range, value must between -9223372036854775807 and 9223372036854775807`
  for a `count` of -9223372036854775808.
- `ERR syntax error` if the third argument is not `WITHVALUES` or there are
  extra arguments.
- `ERR count is too large, the reply would exceed 512 MB` if a negative
  `count` would build a reply larger than 512 MB.
- `WRONGTYPE` if `key` holds a value that is not a hash.

## Examples

```
127.0.0.1:6379> HSET color r 255 g 128 b 0
(integer) 3
127.0.0.1:6379> HRANDFIELD color
"g"
127.0.0.1:6379> HRANDFIELD color 2 WITHVALUES
1) "b"
2) "0"
3) "r"
4) "255"
127.0.0.1:6379> HRANDFIELD color -4
1) "r"
2) "r"
3) "b"
4) "g"
```

The fields you get back are random, so your output will differ.

## Compatibility

Same as Redis 7.4 and Valkey 8.

## See also

[HGETALL](https://docs.hotkv.com/commands/hgetall/index.md), [HSCAN](https://docs.hotkv.com/commands/hscan/index.md), [SRANDMEMBER](https://docs.hotkv.com/commands/srandmember/index.md),
[ZRANDMEMBER](https://docs.hotkv.com/commands/zrandmember/index.md)