0
0
Redisquery~5 mins

RENAME and RENAMENX in Redis

Choose your learning style9 modes available
Introduction

These commands change the name of a key in the database. It helps you organize or update your data by giving keys new names.

You want to change a key's name to something more meaningful.
You need to avoid overwriting an existing key when renaming.
You want to move data from one key to another without losing it.
You want to rename a key only if the new name does not exist yet.
Syntax
Redis
RENAME oldkey newkey
RENAMENX oldkey newkey

RENAME changes the key name and overwrites the new key if it exists.

RENAMENX changes the key name only if the new key does not exist; otherwise, it does nothing.

Examples
This renames the key user:1 to user:100. If user:100 exists, it will be overwritten.
Redis
RENAME user:1 user:100
This renames user:1 to user:100 only if user:100 does not exist. If it exists, the command does nothing.
Redis
RENAMENX user:1 user:100
Sample Program

This example shows how RENAME overwrites the key user:100 with user:1's value. Then it resets user:1 and tries RENAMENX, which does not rename because user:100 exists.

Redis
SET user:1 "Alice"
SET user:100 "Bob"
RENAME user:1 user:100
GET user:100
SET user:1 "Alice"
RENAMENX user:1 user:100
GET user:100
GET user:1
OutputSuccess
Important Notes

If the old key does not exist, both commands return an error.

RENAME can overwrite existing keys, so use it carefully.

RENAMENX returns 1 if the rename was successful, 0 if not.

Summary

RENAME changes a key's name and overwrites if needed.

RENAMENX changes a key's name only if the new name is free.

Use these commands to organize or update your Redis keys safely.