Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How RENAME statement works actually? [closed]

Tags:

sql

mysql

To rename any table in SQL we use following command:

RENAME OldTableName TO NewTableName

How does this work internally?

My assumption is it probably first creates a table with NewTableName using AS SELECT, then deletes the old table with DROP, just like we did when renaming files when handling files in C. Am I right, or does it work differently?

like image 410
A.s. Bhullar Avatar asked Nov 30 '25 14:11

A.s. Bhullar


2 Answers

It works differently. The data isn't copied. The name of the table is simply updated in the metadata tables -- along with references to things like triggers, and so on.

like image 83
Gordon Linoff Avatar answered Dec 03 '25 03:12

Gordon Linoff


You may get some help from here:-

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). ...............

When you execute RENAME, you cannot have any locked tables or active transactions. You must also have the ALTER and DROP privileges on the original table, and the CREATE and INSERT privileges on the new table.

If MySQL encounters any errors in a multiple-table rename, it does a reverse rename for all renamed tables to return everything to its original state.

like image 34
Rahul Tripathi Avatar answered Dec 03 '25 05:12

Rahul Tripathi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!