How to Rename a Key in Redis Without Fear of Overwriting any Existing Keys

If you need to rename a key in Redis, you may be wondering how to do it without overwriting any existing keys. If you use the RENAME command, and a key already exists with your new key name, you’ll overwrite the existing key.

Fortunately, Redis also has a RENAMENX command, which only renames the key if there’s no other key with the new name. So we can use this command whenever we need to rename a key without fear of overwriting any existing keys.

Example

Let’s create two sets and store them in a key called bands and another called groups:

SADD bands Soundgarden ABBA Aerosmith
SADD groups Boston Chicago Devo

Now let’s use RENAMENX to rename the bands key:

RENAMENX bands artists

Result:

(integer) 1

The operation succeeded because there wasn’t an existing key called artists.

Now let’s try to rename the groups key to artists:

RENAMENX groups artists

Result:

(integer) 0

This time nothing was renamed. This is because there’s already a key called artists, and the RENAMENX command won’t overwrite any existing keys.

As alluded to, if you do want to overwrite any existing keys, use the RENAME command.