Redis RANDOMKEY Command Explained

In Redis, the RANDOMKEY command returns a random key from the currently selected database.

Syntax

The syntax goes like this:

RANDOMKEY

So, no arguments are required (or accepted).

Example

Suppose we have the following keys in our database:

KEYS *

Result:

1) "listname"
2) "named_color"
3) "age"
4) "color"
5) "name"
6) "lastname"
7) "colour"
8) "firstname"

We can go ahead and enter the RANDOMKEY command to return a random key:

RANDOMKEY

Result:

"named_color"

And running it again returns another random key:

RANDOMKEY

Result:

"firstname"

The Redis CLI allows us to specify how many times to run a command by simply prefixing it with a number. Therefore, we can return multiple random keys like this:

6 RANDOMKEY

Result:

"age"
"named_color"
"name"
"colour"
"age"
"listname"

In this case I specified to run the command six times, and so we got six random keys.

No Arguments

As mentioned, the RANDOMKEY command doesn’t accept any arguments, at least, not in the current version (7.0.0) at the time of writing.

Here’s what happens if we try to pass an argument:

RANDOMKEY oops

Result:

(error) ERR wrong number of arguments for 'randomkey' command