Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to copy a table in mysql?

Tags:

sql

mysql

I want to copy a table in MySQL. What is the fastest way? Like this?

CREATE TABLE copy LIKE original; INSERT INTO copy SELECT * FROM original; 

or

CREATE TABLE copy SELECT * FROM original; ALTER TABLE copy ADD PRIMARY KEY (id); 

or is there another way?

EDIT: I'm worried about the indexes being re-created, how does mysql proceed executing these statements?

PS. can't use command-line tools like mysqldump, must be on-the-fly.

like image 266
Anon Avatar asked May 31 '10 12:05

Anon


People also ask

How do you duplicate a table?

In Object Explorer, right-click Tables and select New Table. In Object Explorer right-click the table you want to copy and select Design. Select the columns in the existing table and, from the Edit menu, select Copy. Switch back to the new table and select the first row.


2 Answers

This copies the structure of the table immediately, but not the data:

CREATE TABLE copy LIKE original; 

This creates all the indexes the original table had.

It works this way in mysql 5.1.39.

like image 110
ceteras Avatar answered Sep 19 '22 18:09

ceteras


The fastest way using MyISAM tables while preserving indexes) and maybe other storage engines is:

CREATE TABLE copy LIKE original; ALTER TABLE copy DISABLE KEYS; INSERT INTO copy SELECT * FROM original; ALTER TABLE copy ENABLE KEYS; 

You want to disable your keys for your database load and then recreate the keys at the end.

Similarly, for InnoDB:

SET unique_checks=0; SET foreign_key_checks=0;  ..insert sql code here.. SET unique_checks=1; SET foreign_key_checks=1; 

(As pointed out in the comments.)

like image 25
ctbrown Avatar answered Sep 22 '22 18:09

ctbrown