Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL efficiently copy all records from one table to another

Tags:

Is there a more-efficent, less laborious way of copying all records from one table to another that doing this:

INSERT INTO product_backup SELECT * FROM product

Typically, the product table will hold around 50,000 records. Both tables are identical in structure and have 31 columns in them. I'd like to point out this is not my database design, I have inherited a legacy system.

like image 955
crmpicco Avatar asked Jun 25 '12 11:06

crmpicco


People also ask

How do I copy all data from a table?

Using SQL Server Management StudioClick the tab for the table with the columns you want to copy and select those columns. From the Edit menu, click Copy. Click the tab for the table into which you want to copy the columns. Select the column you want to follow the inserted columns and, from the Edit menu, click Paste.

How copy data from existing table to new table in SQL?

The SQL INSERT INTO SELECT Statement The INSERT INTO SELECT statement copies data from one table and inserts it into another table. The INSERT INTO SELECT statement requires that the data types in source and target tables match. Note: The existing records in the target table are unaffected.


2 Answers

There's just one thing you're missing. Especially, if you're using InnoDB, is you want to explicitly add an ORDER BY clause in your SELECT statement to ensure you're inserting rows in primary key (clustered index) order:

INSERT INTO product_backup SELECT * FROM product ORDER BY product_id

Consider removing secondary indexes on the backup table if they're not needed. This will also save some load on the server.

Finally, if you are using InnoDB, reduce the number of row locks that are required and just explicitly lock both tables:

LOCK TABLES product_backup WRITE;
LOCK TABLES product READ;
INSERT INTO product_backup SELECT * FROM product ORDER BY product_id;
UNLOCK TABLES;

The locking stuff probably won't make a huge difference, as row locking is very fast (though not as fast as table locks), but since you asked.

like image 92
Marcus Adams Avatar answered Oct 01 '22 20:10

Marcus Adams


mysqldump -R --add-drop-table db_name table_name > filepath/file_name.sql

This will take a dump of specified tables with a drop option to delete the exisiting table when you import it. then do,

mysql db_name < filepath/file_name.sql
like image 21
satdev86 Avatar answered Oct 01 '22 18:10

satdev86