How do I copy or clone or duplicate the data, structure, and indices of a MySQL table to a new one?
This is what I\'ve found so far.
This will copy the data
The better way to duplicate a table is using only DDL
statement. In this way, independently from the number of records in the table, you can perform the duplication instantly.
My purpose is:
DROP TABLE IF EXISTS table_name_OLD;
CREATE TABLE table_name_NEW LIKE table_name;
RENAME TABLE table_name TO table_name_OLD;
RENAME TABLE table_name _NEW TO table_name;
This avoids the INSERT AS SELECT
statement that, in case of table with a lot of records can take time to be executed.
I suggest also to create a PLSQL procedure as the following example:
DELIMITER //
CREATE PROCEDURE backup_table(tbl_name varchar(255))
BEGIN
-- DROP TABLE IF EXISTS GLS_DEVICES_OLD;
SET @query = concat('DROP TABLE IF EXISTS ',tbl_name,'_OLD');
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- CREATE TABLE GLS_DEVICES_NEW LIKE GLS_DEVICES;
SET @query = concat('CREATE TABLE ',tbl_name,'_NEW LIKE ',tbl_name);
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- RENAME TABLE GLS_DEVICES TO GLS_DEVICES_OLD;
SET @query = concat('RENAME TABLE ',tbl_name,' TO ',tbl_name,'_OLD');
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- RENAME TABLE GLS_DEVICES_NEW TO GLS_DEVICES;
SET @query = concat('RENAME TABLE ',tbl_name,'_NEW TO ',tbl_name);
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END//
DELIMITER ;
Have a nice day! Alex