The RENAME TABLE
statement is used to change the name of an existing table. This operation is useful when you want to modify the name of a table in the database without having to drop and recreate it.
Syntax:
RENAME TABLE old_table_name TO new_table_name;
Parameters:
old_table_name
: The current name of the table that you want to rename.new_table_name
: The new name that you want to assign to the table.
Example:
If you have a table called customers
and you want to rename it to clients
, you would use:
RENAME TABLE customers TO clients;
Renaming Multiple Tables:
MySQL allows you to rename multiple tables in a single RENAME TABLE
statement. You can do this by separating each table name pair (old and new) with commas.
For example, to rename employees
to staff
and orders
to sales_orders
, you can use:
RENAME TABLE employees TO staff, orders TO sales_orders;
Important Notes:
- Atomic Operation: The
RENAME TABLE
statement is atomic, which means it’s performed as a single, indivisible operation. If an error occurs during the renaming, the operation will be rolled back to maintain consistency. - Permissions: You need to have the appropriate privileges to rename tables. Typically, this requires the
ALTER
andDROP
privileges on the table. - Dependencies: Renaming a table does not automatically update references to the table in triggers, views, or foreign keys. You may need to manually update any dependent objects if you rename a table.
- Table Locks: MySQL will acquire table locks when renaming a table, which could impact other operations. However, this is usually a brief operation.
Conclusion:
The RENAME TABLE
statement in MySQL allows you to change the name of a table in the database. It’s a straightforward operation that helps you manage your database schema when table names need to be adjusted. Just ensure that you have the necessary permissions and handle any dependencies that might exist due to the renaming.