How to Use HDEL Command in Redis to Delete Hash Fields
Use the
HDEL command in Redis to delete one or more fields from a hash stored at a key. The syntax is HDEL key field [field ...], which removes specified fields and returns the number of fields deleted.Syntax
The HDEL command removes one or more specified fields from a hash stored at a given key.
- key: The name of the hash.
- field: One or more fields within the hash to delete.
The command returns the number of fields that were actually removed.
redis
HDEL key field1 [field2 ...]
Example
This example shows how to create a hash, delete fields using HDEL, and check the result.
redis
127.0.0.1:6379> HSET user:1000 name "Alice" age "30" city "Paris" (integer) 3 127.0.0.1:6379> HDEL user:1000 age city (integer) 2 127.0.0.1:6379> HGETALL user:1000 1) "name" 2) "Alice"
Output
3
2
1) "name"
2) "Alice"
Common Pitfalls
Common mistakes when using HDEL include:
- Trying to delete fields from a key that does not exist, which returns 0 because no fields were removed.
- Specifying fields that do not exist in the hash, which also returns 0 for those fields.
- Confusing
HDELwithDEL, whereDELdeletes the entire key, not just fields.
redis
127.0.0.1:6379> HDEL user:999 age (integer) 0 # Key does not exist 127.0.0.1:6379> HDEL user:1000 height (integer) 0 # Field does not exist 127.0.0.1:6379> DEL user:1000 (integer) 1 # Deletes entire hash key
Output
0
0
1
Quick Reference
| Command | Description | Return Value |
|---|---|---|
| HDEL key field | Deletes specified field(s) from hash at key | Number of fields removed |
| HDEL key field1 field2 | Deletes multiple fields at once | Number of fields removed |
| DEL key | Deletes entire key and all its data | 1 if key deleted, 0 if not found |
Key Takeaways
HDEL deletes one or more fields from a hash without removing the entire key.
It returns the count of fields that were actually removed.
Deleting non-existing fields or from non-existing keys returns 0.
Use DEL to remove the entire hash key, not HDEL.
Always specify the key and at least one field to delete with HDEL.