views:

96

answers:

6

Hi folks, I want to duplicate a very large table, but I do not want to copy it row by row. Is there a way to duplicate it?

For example, you can TRUNCATE w/o deleting row/row, so i was wondering if there is something similar for copying entire tables

UPDATE: row by row insert is very painful (because of 120M rows). Anyway to avoid that?

+5  A: 

MySQL no longer has a reliable "copy table" functionality - many reasons for this related to how data is stored. However, the below does row-by-row insertion but is pretty simple:

CREATE TABLE `new_table` LIKE `old_table`;
INSERT INTO `new_table` (SELECT * FROM `old_table`);
AvatarKava
+1 for ninja'ing me. [laughs]
pinkgothic
ouch. I have a large table, and the row by row insert is very painful
ming yeow
I hate that! :)
AvatarKava
+4  A: 

You could use INSERT INTO ... SELECT.

pinkgothic
Unfortunately, this won't work as well as the answer @AvatarKava provided, as this will not copy attributes like auto_increment...
gms8994
Mrh? Our answers are identical, excepting @AvatarKava's mentions the create-table line that I only implied (which is also why I upvoted them), and I in turn linked to the documentation. Otherwise we're saying the exact same thing. o.@;
pinkgothic
+1  A: 
INSERT INTO TABLE2 SELECT * FROM TABLE1
modz0r
Unfortunately, this won't work as well as the answer @AvatarKava provided, as this will not copy attributes like auto_increment...
gms8994
Well, the only way to copy those is to recreate them imo.. but true, that alone won't do the trick.
modz0r
+2  A: 

If you're using MyISAM you can copy the physical files on disk. Restart the service and you'll have the new table with indexes and everything the same.

Cfreak
I am using innodb. Does that apply?
ming yeow
unfortunately no :(
AvatarKava
why not though? Curious!
ming yeow
innodb stores data in one big file (I believe you can change this setting in my.cnf but it's rarely if ever turned on), while MyISAM separates each table into a separate set of files.
AvatarKava
no it doesn't work with InnoDB. Another option would be to dump the table and data using mysqldump and then change it's name in the file created and reload it. It's still one row at a time but it's faster because it uses extended INSERT syntax.
Cfreak
A: 

It's nontrivial to copy a large table; ultimately the database is likely to need to rebuild it.

In InnoDB the only way is really to rebuild it, which means insert ... select or such like, however, with 120M rows as it's going to happen in a single transaction, you will probably exceed the size of the rollback area, which will cause the insert to fail.

mysqldump followed by renaming the original table then restoring the dump should work, as mysqldump may cause a commit every lots of rows. However it will be slow.

MarkR
A: 

oracle:

Create table t as select * from original_table

Randy