Redis RENAMENX Command Explained

In Redis, the RENAMENX command renames a key, but only if the new key doesn’t already exist.

RENAMENX is similar to the RENAME command, except that it only renames the key if the new one doesn’t already exist. The RENAME command on the other hand, will overwrite the new key if it already exists.

Syntax

The syntax goes like this:

RENAMENX key newkey

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

Example

Here’s an example to demonstrate:

RENAMENX colour color

Result:

(integer) 1

In this case I renamed a key called colour to color. The operation was successful and so we got an integer reply of 1.

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

The key is not renamed if the new key already exists.

Let’s try to rename another key to one that already exists:

RENAMENX named_color color

Result:

(integer) 0

An integer reply of 0 is returned, which means that the key was not renamed.

I can verify this by running the KEYS command:

KEYS named_color

Result:

1) "named_color"

This is the whole point of the RENAMENX command. It doesn’t rename a key if the new one already exists. To overwrite an existing key, use RENAME instead.

When the Old Key Doesn’t Exist

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

RENAMENX nonexistentkey newkey

Result:

(error) ERR no such key