RENAME TABLE a TO b, c TO d renames atomically, so a rebuilt copy can replace a table without any query finding it missing, and RENAME TABLE shop.a TO archive.a moves a table between databases.
RENAME TABLE customers_archive TO customers_old, country_counts TO stats_by_country;
DROP TABLE customers;
DROP TABLE customers_old, no_such_table;
CREATE TABLE products_new LIKE products;
INSERT INTO products_new SELECT * FROM products;
RENAME TABLE products TO products_old, products_new TO products;
SELECT CONSTRAINT_NAME, REFERENCED_TABLE_NAME FROM information_schema.REFERENTIAL_CONSTRAINTS
WHERE CONSTRAINT_SCHEMA = 'shop' AND TABLE_NAME = 'order_items';ERROR 3730 (HY000): Cannot drop table 'customers' referenced by a foreign key constraint 'reviews_ibfk_2' on table 'reviews'. ERROR 1051 (42S02): Unknown table 'shop.no_such_table' +--------------------+-----------------------+ | CONSTRAINT_NAME | REFERENCED_TABLE_NAME | +--------------------+-----------------------+ | fk_items_order | orders | | order_items_ibfk_2 | products_old | +--------------------+-----------------------+
Foreign keys follow the table, not the name: order_items now points at products_old, and the new products has no foreign keys because LIKE skips them, so re-point child keys before dropping the old copy. DROP TABLE is atomic since MySQL 8.0 524 : the failed statement left customers_old in place. IF EXISTS turns error 1051 into a note. TRUNCATE TABLE (compared with DELETE in DELETE, TRUNCATE, and REPLACE) re-creates the table, commits implicitly and resets AUTO_INCREMENT: after truncating page_views, the next row got my_row_id 1.