content/commands/srandmember.md
When called with just the key argument, return a random element from the set value stored at key.
If the provided count argument is positive, return an array of distinct elements.
The array's length is either count or the set's cardinality ([SCARD]({{< relref "/commands/scard" >}})), whichever is lower.
If called with a negative count, the behavior changes and the command is allowed to return the same element multiple times.
In this case, the number of returned elements is the absolute value of the specified count.
{{% redis-cli %}} SADD myset one two three SRANDMEMBER myset SRANDMEMBER myset 2 SRANDMEMBER myset -5 {{% /redis-cli %}}
When the count argument is a positive value this command behaves as follows:
count is bigger than the set's cardinality, the command will only return the whole set without additional elements.When the count is a negative value, the behavior changes as follows:
count elements, or an empty array if the set is empty (non-existing key), are always returned.Note: this section is relevant only for Redis 5 or below, as Redis 6 implements a fairer algorithm.
The distribution of the returned elements is far from perfect when the number of elements in the set is small, this is due to the fact that we used an approximated random element function that does not really guarantees good distribution.
The algorithm used, that is implemented inside dict.c, samples the hash table buckets to find a non-empty one. Once a non empty bucket is found, since we use chaining in our hash table implementation, the number of elements inside the bucket is checked and a random element is selected.
This means that if you have two non-empty buckets in the entire hash table, and one has three elements while one has just one, the element that is alone in its bucket will be returned with much higher probability.
| Redis Software | Redis Cloud | <span style="min-width: 9em; display: table-cell">Notes</span> | |:----------------------|:-----------------|:------| | <span title="Supported">✅ Standard</span> <span title="Supported"><nobr>✅ Active-Active</nobr></span> | <span title="Supported">✅ Standard</span> <span title="Supported"><nobr>✅ Active-Active</nobr></span> | |
{{< multitabs id="srandmember-return-info" tab1="RESP2" tab2="RESP3" >}}
One of the following:
-tab-sep-
One of the following:
{{< /multitabs >}}