# ZRANDMEMBER

> Return one or more random members of a sorted set, optionally with their scores.

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

```
ZRANDMEMBER key [count [WITHSCORES]]
```

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

`ZRANDMEMBER` picks random members from the sorted set at `key` without
changing it.

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

## Options

| Option | Effect |
| --- | --- |
| `count` | How many members to return, as described above. |
| `WITHSCORES` | Return each member with its score. Only valid after `count`. |

`count` and `WITHSCORES` are checked before the key is looked up.

## Return value

| Case | RESP2 | RESP3 |
| --- | --- | --- |
| No `count` | Bulk string: a member, or nil bulk string if the key does not exist | Bulk string, or null |
| With `count` | Array of members (empty if the key does not exist) | Same |
| With `count` and `WITHSCORES` | Flat array: member, score, ... (scores as bulk strings) | Array of `[member, score]` pairs, the score a double |

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 `WITHSCORES` 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 sorted set.

## Examples

```
127.0.0.1:6379> ZADD board 1 "a" 2 "b" 3 "c"
(integer) 3
127.0.0.1:6379> ZRANDMEMBER board
"b"
127.0.0.1:6379> ZRANDMEMBER board 2 WITHSCORES
1) "c"
2) "3"
3) "a"
4) "1"
127.0.0.1:6379> ZRANDMEMBER board -3
1) "a"
2) "a"
3) "c"
```

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

## Compatibility

Same as Redis 7.4 and Valkey 8.

## See also

[ZRANGE](https://docs.hotkv.com/commands/zrange/index.md), [ZSCAN](https://docs.hotkv.com/commands/zscan/index.md), [SRANDMEMBER](https://docs.hotkv.com/commands/srandmember/index.md),
[HRANDFIELD](https://docs.hotkv.com/commands/hrandfield/index.md)