2 Ways to Rename a Key in Redis

There are a couple of commands that enable us to rename a key in Redis. The one we use will depend on whether or not we want to overwrite any existing keys.

The RENAME Command

One is the RENAME command. This command does exactly what it promises – allows us to rename a given key.

Example:

RENAME surname lastname

Result:

OK

Here, I renamed the surname key to lastname.

When using this command, if there’s already a key with the new name, it’s overwritten. If you don’t want this to happen, use the RENAMENX command instead.

The RENAMENX Command

As I alluded to, the RENAMENX command renames the key only if there’s not already a key with the new name. Therefore, we can use this if we don’t want to accidentally overwrite an existing key.

Example:

RENAMENX lastname surname

Result:

(integer) 1

This command returns an integer reply of 1 if the key was renamed, and 0 if it wasn’t (due to the key already existing).

Here’s an example of trying to rename a key to one that already exists:

RENAMENX firstname username

Result:

(integer) 0

In my case, I already had a key called username, so nothing was renamed.