Redis RENAME Command Explained

In Redis, the RENAME command renames a key. It allows us to give a key a new name.

Syntax

The syntax goes like this:

RENAME key newkey

Where key is the old key name and newkey is the new one.

Example

Here’s an example to demonstrate:

RENAME colour color

Result:

OK

In this case I renamed a key called colour to color.

Let’s check its value:

GET color

Result:

"Red"

If we use the KEYS command to check whether the original key exists, we can see that it doesn’t:

KEYS colour

Result:

(empty array)

When the New Key Already Exists

If the new key already exists, it is overwritten. More specifically, Redis performs an implicit DEL operation (which could impact performance if the key’s value is large).

Here’s an example of renaming a key to key that already exists:

RENAME named_color color

Result:

OK

Here, the new key is the same one I used in the previous example, but the old key is a different one.

Now when I get the value of the color key, it contains a different value:

GET color

Result:

"Green"

In the previous example, this key had a value of Red, but now it has a value of Green. That’s because the named_color key had a value of Green.

When the Old Key Doesn’t Exist

If we try to rename a key that doesn’t exist, an error is returned:

RENAME nonexistentkey newkey

Result:

(error) ERR no such key

Also see the Redis RENAMENX command, which only renames the key if the new one doesn’t already exist.