How to Delete a Key in Redis: Simple Syntax and Examples
To delete a key in Redis, use the
DEL command followed by the key name. For example, DEL mykey removes the key named mykey from the database.Syntax
The DEL command removes one or more keys from Redis. If the key exists, it is deleted; if not, Redis ignores it.
DEL key1 [key2 ...]: Deletes specified keys.- Returns the number of keys that were actually removed.
redis
DEL key1
Output
(integer) 1
Example
This example shows how to set a key, delete it, and check if it still exists.
redis
SET mykey "Hello"
DEL mykey
EXISTS mykeyOutput
(integer) 1
(integer) 1
(integer) 0
Common Pitfalls
One common mistake is trying to delete a key that does not exist, which returns 0 but does not cause an error. Another is confusing DEL with UNLINK, which deletes keys asynchronously.
Also, deleting keys in a pipeline or transaction requires care to check results properly.
redis
DEL nonexistingkey
-- returns (integer) 0
-- Correct usage:
DEL existingkeyOutput
(integer) 0
(integer) 1
Quick Reference
| Command | Description | Return Value |
|---|---|---|
| DEL key | Deletes the specified key | Number of keys deleted (0 or 1) |
| DEL key1 key2 | Deletes multiple keys at once | Number of keys deleted |
| EXISTS key | Checks if a key exists | 1 if exists, 0 if not |
Key Takeaways
Use the DEL command followed by the key name to delete keys in Redis.
DEL returns the number of keys it successfully deleted, which can be zero if the key does not exist.
You can delete multiple keys at once by listing them after DEL.
Deleting a non-existing key does not cause an error, it simply returns 0.
For asynchronous deletion, consider using UNLINK instead of DEL.