How to Update a Key and Return its Old Value in a Single Operation in Redis

When using the SET command to set a key in Redis, we can use the GET option to return its old value. This allows us to update the value of a key while returning the value that we’re replacing it with.

Note that this option was introduced in Redis 7.0.0, so if it doesn’t work, check your Redis version. If using an earlier version, try the GETSET command instead (which is deprecated from Redis version 6.2.0).

Example

Suppose we set a key like this:

SET color "Green"

Result:

OK

When setting a value like this, we get an OK when the key is set successfully.

We might typically get its value with the GET command:

GET color

Result:

"Green"

But let’s say we want to return the key’s value but also set its value to something else. In that case we can do this:

SET color "Red" GET

Result:

"Green"

So when we use the GET option, instead of getting a response of OK, we get the key’s old value.