Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to duplicate a table with keys & other structure features retained in MySQL?

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.

like image 299
jondinham Avatar asked Nov 22 '11 12:11

jondinham


People also ask

How do I copy just the structure of a table in SQL?

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.

How do you duplicate a 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.

How can I create a duplicate table in DBMS?

Right-click the table you want to copy in Database Explorer and select Duplicate Object.


1 Answers

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

like image 91
Shirish11 Avatar answered Sep 19 '22 13:09

Shirish11