Redis HDEL Command

In Redis, the HDEL command enables us to delete one or more fields in a hash. It deletes the specified field/s at the specified key.

If the field doesn’t exist, it’s ignored. If the key doesn’t exist, it’s treated as an empty hash and 0 is returned.

Syntax

The syntax goes like this:

HDEL key field [field ...]

This shows us that we can delete multiple fields in the key.

Example

Suppose we set the following hash:

HSET customer firstname "Rob" lastname "Banks" age 35 nationality "Australian"

Result:

(integer) 4

We set a hash called customer with four field/value pairs.

Let’s use HKEYS to get all the fields in our hash:

HKEYS customer

Result:

1) "firstname"
2) "lastname"
3) "age"
4) "nationality"

We can see that there are four fields in the hash.

Let’s use the HDEL command to delete two fields:

HDEL customer age nationality

Result:

(integer) 2

Two fields were deleted as expected.

Let’s check the key for its remaining fields:

HKEYS customer

Result:

1) "firstname"
2) "lastname"

As expected, only two fields remain.

Non-Existent Fields

If the field doesn’t exist within the hash, it’s ignored:

HDEL customer age nationality

Result:

(integer) 0

We get a 0 as expected.

Here, we ran the same code as before, but this time the fields didn’t exist (because we had already deleted them in the previous example).

Non-Existent Keys

Running the command against a key that doesn’t exist treats it as an empty hash, and 0 is returned:

HDEL nonexistentkey firstname

Result:

(integer) 0

Trying to Delete a non-Hash Key

If the key exists, but it’s not a hash, we get an error:

HDEL color name

Result:

(error) WRONGTYPE Operation against a key holding the wrong kind of value

In this case, the color key is actually a string. So Redis prevented it from being updated and returned this error message.

Passing the Wrong Number of Arguments

Passing the wrong number of arguments results in an error:

HDEL customer

Result:

(error) ERR wrong number of arguments for 'hdel' command