Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying a Table in MySQL and including the Primary Key

Tags:

sql

mysql

I have an ancient code snippet I use for copying tables in MySQL.

CREATE TABLE new_table (select * from old_table);

This works great, with one exception. It doesn't copy the primary key or other table indexes.

Is there any way to copy a table in MySQL AND include the indexes/primary key??

like image 478
Alan Storm Avatar asked Oct 19 '25 14:10

Alan Storm


1 Answers

Theres one of two ways. To see how a table is built you can use

SHOW CREATE TABLE old_table

You could also (I think you'll have to test it), run this:

CREATE TABLE new_table LIKE old_table;
INSERT INTO new_table SELECT * FROM old_table;
like image 88
cdnicoll Avatar answered Oct 21 '25 07:10

cdnicoll



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!