0
0
RedisHow-ToBeginner · 3 min read

How to Check if a Key Exists in Redis

To check if a key exists in Redis, use the EXISTS command followed by the key name. It returns 1 if the key exists and 0 if it does not.
📐

Syntax

The EXISTS command checks if one or more keys exist in Redis.

  • EXISTS key: Checks if a single key exists.
  • The command returns 1 if the key exists, otherwise 0.
  • You can also check multiple keys at once, and it returns the count of keys that exist.
redis
EXISTS key
💻

Example

This example shows how to check if a key named user:1000 exists in Redis.

redis
127.0.0.1:6379> SET user:1000 "Alice"
OK
127.0.0.1:6379> EXISTS user:1000
(integer) 1
127.0.0.1:6379> EXISTS user:2000
(integer) 0
Output
(integer) 1 (integer) 0
⚠️

Common Pitfalls

Some common mistakes when checking if a key exists in Redis:

  • Using GET to check existence can return null if the key does not exist, but it also returns the value if it exists, which is less efficient.
  • Confusing the return value: EXISTS returns 1 or 0, not true or false.
  • When checking multiple keys, EXISTS returns the count of existing keys, not a boolean.
redis
/* Wrong way: Using GET to check existence */
GET user:1000

/* Right way: Using EXISTS to check existence */
EXISTS user:1000
📊

Quick Reference

Summary of the EXISTS command usage:

CommandDescriptionReturn Value
EXISTS keyCheck if a single key exists1 if exists, 0 if not
EXISTS key1 key2Check how many keys existNumber of keys that exist

Key Takeaways

Use the EXISTS command to efficiently check if a key exists in Redis.
EXISTS returns 1 if the key exists and 0 if it does not.
Avoid using GET to check existence as it is less efficient and returns the value.
When checking multiple keys, EXISTS returns the count of existing keys, not a boolean.
Remember EXISTS returns integers, not true/false values.