tags:

views:

124

answers:

6

which one is the fastest way to completely copy a table on mysql ?

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 theres 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.

A: 

As with most questions like this, I would suggest you try it on your own particular installation, against the particular tables you wish to copy.

Brian Agnew
but does the indexes gets copied in any of alternatives ? I would like to know how mysql execute these options
Anon
@Anon that wasn't your question though. Perhaps you can edit it to clarify the points that you actually want to know.
Martin Smith
@Martin Smith sorry you are right, I edited.
Anon
+2  A: 

Try SELECT INTO, and use a variable as a go-between.

You'll have to create the receiving table, first, to have the same structure as the source table.

Best thing is, it's internal so it's fast. You'll lose your indexes, though.

amphetamachine
Select into is not supported by mySQL
Draco Ater
@Draco Ater - Yes, it does. It just uses variables.
amphetamachine
A: 

Does create table mynewtable (select * from myoldtable) work in mysql? If so you can try it too.

Draco Ater
yea it works but it doesn't copy the indexes.
Anon
+2  A: 

You shouldn't be concerned in the speed of this operation.
As it's obviously shouldn't be done on a regular basis, and for the single case it isn't so important

Col. Shrapnel
A: 

From the manual:

"CREATE TABLE ... SELECT does not automatically create any indexes for you. This is done intentionally to make the statement as flexible as possible. If you want to have indexes in the created table, you should specify these before the SELECT statement: "

CREATE TABLE bar (UNIQUE (n)) SELECT n FROM foo;

You can specify indices and data types (to avoid datatype conversion) in with both CREATE TABLE LIKE and CREATE TABLE SELECT. Which one is faster will depend on your setup.

dnagirl
nice, gonna test this one together with the other 2, thank you
Anon
A: 
CREATE TABLE copy LIKE original;

This creates all the indexes the original table had. At least it works this way in mysql 5.1.39.

ceteras