0
0
Redisquery~5 mins

EXISTS to check key existence in Redis

Choose your learning style9 modes available
Introduction
We use EXISTS to quickly check if a key is present in the database without retrieving its value.
Before updating a key, to make sure it exists.
To check if a user session key is active.
To verify if a cache entry is available before fetching data.
To conditionally perform actions only if a key is stored.
To avoid errors when deleting keys that might not exist.
Syntax
Redis
EXISTS key [key ...]
You can check one or multiple keys at once by listing them.
The command returns the number of keys that exist among the given keys.
Examples
Check if the key 'user:1000' exists.
Redis
EXISTS user:1000
Check if both 'session:1234' and 'cart:5678' keys exist; returns how many exist.
Redis
EXISTS session:1234 cart:5678
Sample Program
First, we set a key 'user:1' with value 'Alice'. Then we check if 'user:1' exists (should be 1). Next, check 'user:2' which was not set (should be 0). Finally, check both keys together; only 'user:1' exists, so result is 1.
Redis
SET user:1 "Alice"
EXISTS user:1
EXISTS user:2
EXISTS user:1 user:2
OutputSuccess
Important Notes
EXISTS returns an integer: the count of keys found, not a boolean true/false.
If you check multiple keys, the result tells how many exist, not which ones.
Use EXISTS to avoid errors when working with keys that might not be present.
Summary
EXISTS checks if one or more keys are in the database.
It returns how many of the given keys exist.
Useful to confirm presence before reading or modifying keys.