The Redis GETDEL
command gets the value of a given key, then deletes that key. It’s similar to the GET
command, except that it deletes the key on success (the GET
command doesn’t delete the key – it only returns its value).
An error is returned if the value stored at key
is not a string.
The GETDEL
command was introduced in Redis 6.2.0.
Syntax
GETDEL key
Where key
is the key for whose value we want returned and deleted.
Example
Suppose we set a key/value pair:
SET type "dog"
In this case, type
the key and "dog"
is its value.
Now that we’ve set the type
key, we can use the GETDEL
command to get its value, then delete the key:
GETDEL type
Result:
"dog"
As expected, the value is returned.
When the Key Doesn’t Exist
If the key doesn’t exist, nil
is returned.
Let’s run the command again:
GETDEL type
Result:
(nil)
We got nil
because the key doesn’t exist. It doesn’t exist because we already deleted it with GETDEL
in the previous example.
Key/value pairs can also expire (if they’ve been assigned an expire time), so if you get a null result when trying to get the value of a key that you are almost certain exists, it could be that it has expired.
Wrong Number of Arguments
Passing the wrong number of arguments, or no arguments at all to GETDEL
results in an error:
GETDEL
Result:
(error) ERR wrong number of arguments for 'getdel' command