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
1if the key exists, otherwise0. - 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
GETto check existence can returnnullif the key does not exist, but it also returns the value if it exists, which is less efficient. - Confusing the return value:
EXISTSreturns1or0, nottrueorfalse. - When checking multiple keys,
EXISTSreturns 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:
| Command | Description | Return Value |
|---|---|---|
| EXISTS key | Check if a single key exists | 1 if exists, 0 if not |
| EXISTS key1 key2 | Check how many keys exist | Number 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.