How to duplicate a table with keys & other structure features retained? including primary key, foreign keys, and indexes.
Can this be done with a single MySQL query?
I'm using "create table newtable as select..." but this method makes all keys & indexes lost.
If you want to copy the data of one SQL table into another SQL table in the same SQL server, then it is possible by using the SELECT INTO statement in SQL. The SELECT INTO statement in Structured Query Language copies the content from one existing table into the new table.
To duplicate a table. Make sure you are connected to the database in which you want to create the table and that the database is selected in Object Explorer. In Object Explorer, right-click Tables and select New Table. In Object Explorer right-click the table you want to copy and select Design.
Right-click the table you want to copy in Database Explorer and select Duplicate Object.
duplicating a table from another table (with indexing and structure)cannot be done with a single query you will need need 2 queries.
1) To create Duplicate table.
CREATE TABLE Table2 LIKE Table1;
This will create an exact copy of the table.
2) Fill in the Duplicate table with values from original table.
INSERT INTO Table2 SELECT * from Table1;
will fill Table2 with all the records fom Table1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With