4 Ways to Delete a Key in Redis

When using Redis, we often have many ways to do the same thing. One example of this is with deleting keys.

Below are four options for deleting keys in Redis.

The DEL Command

The most obvious option is the DEL command. This is a generic command that deletes the specified key/s.

Example:

DEL user

Result:

(integer) 1

This command returns the number of keys that were deleted.

We can delete more than one key at once with this command. Therefore, we can do the following:

DEL user age pets

Result:

(integer) 3

In this case all three keys were deleted.

The GETDEL Command

The GETDEL command is a string command that returns the value of a key and then deletes it.

Example:

GETDEL user

Result:

"Homer"

In this case the value of the key was Homer. The key was deleted once its value was returned. To verify this, we can run the command again:

GETDEL user

Result:

(nil)

The UNLINK Command

The UNLINK command is a generic command that’s similar to the DEL command in that it removes the specified keys. However, the UNLINK command performs the actual memory reclaiming in a different thread, so it is not blocking, whereas DEL is.

Here’s an example of using UNLINK:

UNLINK user

Result:

(integer) 1

As with DEL, the UNLINK command allows us to delete/unlink multiple keys at once:

UNLINK user age pets

Result:

(integer) 3

Expire the Key

Another way to delete a key is to use a command that expires it. For example we can use EXPIRE to specify an amount in seconds or PEXPIRE to specify an amount in milliseconds. We can alternatively use EXPIREAT to specify the Unix timestamp in seconds, or PEXPIREAT to specify the Unix timestamp in milliseconds.

Here’s an example of using EXPIRE:

EXPIRE user 0

Result:

(integer) 1

In this case I specified an expiry of 0, which expired the key immediately. Now when I try to access the key, I get nil:

GET user

Result:

(nil)

An alternative option is to specify the amount as a Unix timestamp. Here’s an example of specifying the Unix timestamp in seconds:

EXPIREAT age 1658540000

Result:

(integer) 1

This Unix timestamp is in the past, and so the key is expired immediately. Now when I try to access it, I get nil:

GET age

Result:

(nil)