Redis Check If Key Exists

Redis is a free, open-source in-memory key-value database used in high-performance applications. Redis is highly scalable and provides a collection of tools and extensions as a primary database for non-trivial applications.

This tutorial will demonstrate how to use the Redis commands to check if a key exists within a specific Redis database.

Redis Set Key

Before exploring how to check if a key exists, we need to insert the sample data. The simplest method is to use the SET command.

Open the terminal and launch the Redis CLI as follows:

$ redis-cli>

In the Redis command-line interface, we can run the SET command followed by a key and its associated value.

The following syntax is as shown:

SET "key” "value"

For example:> SET user1 "first_user"


The SET command returns OK if the SET operation is executed successfully. If the command fails, the return value is NIL.

You can also store a numerical value as the key. An example is provided below:> SET 0 "First"


The previous command sets the key 0 with the associated value as the string “First.”

Redis GET Key

After setting a key, you can retrieve the value stored in it using the GET command. The syntax is shown below:

GET <key>

For example, to get the value stored in the key user1, you can run the following command:> GET user1


In some instances, you may have a key holding the numerical value 0. Take the following example:> SET balance 0


In the previous command, we have the key “balance” holding 0. Therefore, if we get the value of the key, we get 0.> GET balance


This can be confusing because we are unsure whether the key is missing or holding the value 0. We can fix this by checking if the key exists.

Redis Check If Key Exists

We use the EXISTS command to check if a key exists in the Redis database. The following syntax is as shown:

EXISTS [key]

An example usage is provided below:> EXISTS balance

(integer) 1

The command returns (integer) 1 if the specified key exists in the database. Otherwise, the command returns (integer) 0.

You can pass multiple keys to the command as shown:> EXISTS user1 balance

(integer) 2

In this case, the command returns the number of keys found.


This tutorial covers creating a key-value pair in Redis, retrieving a value using the specified key, and checking if a key exists in the database. We hope you found this article helpful. Check the other Linux Hint articles for more tips and information.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list