Redis EXISTS Command Explained

In Redis, the EXISTS command checks whether the specified keys exist. It returns an integer reply with the number of keys that exist.

We can use the command to check for the existence of one key or multiple keys.

Syntax

The syntax goes like this:

EXISTS key [key ...]

Where key is each key to check. This syntax indicates that we can check for as many keys as we need, simply by appending them to the previous key (with a space between).

Example

Here’s an example of using EXISTS to check for a single key:

EXISTS pets

Result:

(integer) 1

In this case I got an integer reply of 1, which means that the key does exist.

Here’s what happens when the key doesn’t exist:

EXISTS nonexistentkey

Result:

(integer) 0

This time we get an integer reply of 0, which means that the key doesn’t exist.

Check Multiple Keys

As mentioned, we can check for the existence of as many keys as we like:

EXISTS pets nonexistentkey score country

Result:

(integer) 3

In this case, three of the four keys do exist and so we get an integer reply of 3.

Duplicate Keys

Be careful not to accidentally include the same key multiple times. Including a key multiple times will result in that key being counted multiple times. So you may get misleading results if the key happens to exist.

Example:

EXISTS pets pets pets

Result:

(integer) 3