How to Rename a Key in Redis: Syntax and Examples
To rename a key in Redis, use the
RENAME oldkey newkey command which changes the key name unconditionally. Alternatively, use RENAMENX oldkey newkey to rename only if the new key does not exist.Syntax
The RENAME command changes the name of an existing key to a new name, overwriting the new key if it exists. The RENAMENX command renames the key only if the new key does not already exist.
RENAME oldkey newkey: Renameoldkeytonewkey, overwritingnewkeyif it exists.RENAMENX oldkey newkey: Renameoldkeytonewkeyonly ifnewkeydoes not exist.
redis
RENAME oldkey newkey RENAMENX oldkey newkey
Example
This example shows how to rename a key user:1 to user:100 using RENAME. It also shows how RENAMENX prevents overwriting an existing key.
redis
127.0.0.1:6379> SET user:1 "Alice" OK 127.0.0.1:6379> RENAME user:1 user:100 OK 127.0.0.1:6379> GET user:100 "Alice" 127.0.0.1:6379> SET user:1 "Bob" OK 127.0.0.1:6379> SET user:100 "Carol" OK 127.0.0.1:6379> RENAMENX user:1 user:100 (integer) 0 127.0.0.1:6379> GET user:1 "Bob" 127.0.0.1:6379> GET user:100 "Carol"
Output
OK
OK
"Alice"
OK
OK
(integer) 0
"Bob"
"Carol"
Common Pitfalls
Common mistakes include trying to rename a key that does not exist, which causes an error, or using RENAME when you want to avoid overwriting an existing key. Use RENAMENX to prevent accidental overwrites. Also, remember that RENAME is atomic, so the key is renamed instantly.
redis
127.0.0.1:6379> RENAME missingkey newkey (error) ERR no such key # Correct approach to avoid overwriting: 127.0.0.1:6379> RENAMENX oldkey newkey (integer) 1 # success if newkey does not exist
Output
(error) ERR no such key
(integer) 1
Quick Reference
| Command | Description | Overwrite Behavior |
|---|---|---|
| RENAME oldkey newkey | Rename key unconditionally | Overwrites newkey if exists |
| RENAMENX oldkey newkey | Rename key only if newkey does not exist | Does not overwrite; returns 0 if newkey exists |
Key Takeaways
Use
RENAME to rename keys unconditionally, overwriting existing keys.Use
RENAMENX to rename keys only if the new key does not exist to avoid overwriting.Renaming a non-existing key with
RENAME causes an error.Both commands operate atomically, ensuring instant rename.
Check key existence before renaming if you want to avoid errors.