0
0
RedisHow-ToBeginner · 3 min read

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 HDEL with DEL, where DEL deletes 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

CommandDescriptionReturn Value
HDEL key fieldDeletes specified field(s) from hash at keyNumber of fields removed
HDEL key field1 field2Deletes multiple fields at onceNumber of fields removed
DEL keyDeletes entire key and all its data1 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.