Redis UNLINK Command Explained

In Redis, the UNLINK command removes the specified keys. It’s similar to the DEL command, except that it performs the memory reclaiming in a different thread, so it is not blocking. The DEL command, on the other hand, doesn’t do this.

More specifically, the UNLINK command unlinks the keys from the keyspace, and then removes it later asynchronously.

Syntax

The syntax goes like this:

UNLINK key [key ...]

Which means we can remove one or more keys at the same time.

Example

Let’s create a key:

SET age 10

Result:

OK

Now that it has been set, we can go ahead and do things like check its value:

GET age

Result:

"10"

Now let’s use UNLINK to remove the key:

UNLINK age

Result:

(integer) 1

We get an integer reply of 1, which means that the key was successfully unlinked.

We can verify this by trying to check its value again:

GET age

Result:

(nil)

A result of nil happens when the key doesn’t exist.

Unlink Multiple Keys

We can remove more than one key with UNLINK.

To demonstrate this, let’s create multiple keys:

MSET name "Bart" age 10 score "150"

Result:

OK

Here, we used MSET to set multiple keys at once.

Let’s use MGET to check their values:

MGET name age score

Result:

1) "Bart"
2) "10"
3) "150"

OK, now let’s use UNLINK to remove all three keys:

UNLINK name age score

Result:

(integer) 3

We get an integer reply of 3, which means that three keys were unlinked.