For the complete documentation index, see llms.txt. This page is also available as Markdown.

RENAME TABLE

Change the name of one or more tables atomically. This command moves tables within or between databases while preserving their data and structure.

Syntax

RENAME TABLE[S] [IF EXISTS] tbl_name 
  [WAIT n | NOWAIT]
  TO new_tbl_name
    [, tbl_name2 TO new_tbl_name2] ...
Railroad diagram of RENAME TABLE — equivalent to the BNF above

Description

This statement renames one or more tables or views, but not the privileges associated with them. For InnoDB tables, it also triggers a reload of InnoDB statistics.

IF EXISTS

If this clause is used, you don't get an error if the table to be renamed doesn't exist.

The rename operation is done atomically, which means that no other session can access any of the tables while the rename is running. For example, if you have an existing table old_table, you can create another table new_table that has the same structure but is empty, and then replace the existing table with the empty one as follows (assuming that backup_table does not already exist):

Moving Tables to Another Database

tbl_name can optionally be specified as db_name.tbl_name. See Identifier Qualifiers. This allows to use RENAME to move a table from a database to another (as long as they are on the same filesystem):

Limitations of Moving Tables to Another Database

Trying to do so produces the following error:

Trying to do so produces the following error:

Renaming Multiple Tables at Once

Multiple tables can be renamed in a single statement. The presence or absence of the optional S (RENAME TABLE or RENAME TABLES) has no impact, whether a single or multiple tables are being renamed.

Renames are always executed in the specified order. Knowing this, it is also possible to swap two tables' names:

WAIT/NOWAIT

Set the lock wait timeout. See WAIT and NOWAIT.

Privileges

Executing the RENAME TABLE statement requires the ALTER and DROP privileges on the original table, and the CREATE and INSERT privileges on the new table.

Atomic RENAME TABLE

RENAME TABLE is atomic for most storage engines, including InnoDB, MyRocks, MyISAM and Aria (MDEV-23842).

This means that if there is a crash (server down or power outage) during RENAME TABLE, all tables revert to their original names and any changes to trigger files are reverted. See Atomic DDL for more information.

RENAME TABLE is not atomic.

There is a small chance that, during a server crash happening in the middle of RENAME TABLE, some tables could have been renamed (in the worst case partly) while others would not be renamed.

This page is licensed: GPLv2, originally from fill_help_tables.sql

spinner

Last updated

Was this helpful?