How to Return a Random Key in Redis

If you ever find yourself in the situation where you need to get a random key when using Redis, take a look at the RANDOMKEY command.

This command returns a random key from the currently selected database.

Example

Here’s an example to demonstrate:

RANDOMKEY

Result:

"customer"

In this case, the command returned a key called customer.

Let’s run it again:

RANDOMKEY

Result:

"dogs"

This time it returned a key called dogs.

In case it’s not obvious, these examples assume that there were keys of those names in the currently selected database.

It doesn’t matter what data type the key holds, the command simply chooses a random key. In our example, the two keys contain two different data types. Let’s check:

TYPE customer

Result:

hash

The first key is a hash.

Let’s check the second key’s type:

TYPE dogs

Result:

set

That key is a set.

As the above examples illustrate, when we call the RANDOMKEY command, we call it without any arguments. At least, that’s the case at the time of writing. You can check the Redis documentation in case this changes.