We have a process which will regenerate a table from scratch, drop the original table, and move the new table into the original's place. Now this should happen very quickly, but sometimes a website request hits the table after it's been dropped but before the new one is renamed. Apart from coding the website to be more robust when there's a database error, is there an easier way to do this?
Mysql – Easily, quickly replace MySQL table
MySQL
Related Question
- Mysql – Simple queries taking ages to run after changing from MyISAM to InnoDB
- MySQL CPU & Memory Spikes
- MySQL – How to Efficiently Swap a Portion of a Large Table’s Data
- Mysql – What could cause a record to appear in the MySQL binary log but not the original table
- Mysql – What happens to thesql information_schema after switching to innodb_file_per_table
- SQLAlchemy – How to Check if a Database Table Has Been Renamed
Best Answer
The
RENAME TABLE
syntax allows for atomic, multiple renames. See as follows:In the above it is impossible for your code to access the table during the
RENAME
operation, and this it cannot happen that the code "does not find the table". It just blocks untilRENAME
operation completes, and the table is always there.Also worth noting that unless using Percona Server with "fast DROP TABLE patch",
DROP
ping a table might hold locks on your database (namely thetable cache
) for the duration of the operation. And the operation may take a while since it involves evacuating table pages from InnoDB's cache and deleting the table file(s) from the filesystem.Waiting for some time (eg a couple hours) after the
RENAME
operation can do good since your old-table's pages are more likely to be flushed out by that time, reducing the overall time fromDROP
ping the table.