When we are doing an insert of huge no.of rows into an SQL table ,Normally we will try to write separate insert quries this may lead us to a long duration of execution time and we can increase the speed of executing SQL quries by adding all the rows into a single insert query.
NORMAL CASE:
eg:INSERT INTO tbl_name(field1,field2,…) values(value1,value2,..); INSERT INTO tbl_name(field1,field2,…) values(value1,value2,..); INSERT INTO tbl_name(field1,field2,…) values(value1,value2,..);
We can decrease the execution time by adding all these rows into a single INSERT query like below,
INSERT INTO tbl_name(field1,field2,…) values(value1,value2,..),values(value1,value2,..),values(value1,value2,..),….;
This is useful when we are trying to insert about 10k of rows into a table at a time. For me normally it takes 1min 15 sec to insert 10k of rows but by using this tip it takes only 10 sec to insert 10k of rows.
i have tried this when i did excel and csv import feature. For excel it took around 20 sec and for csv it took 10 sec of execution time for inseting 10k of rows.
Reagards,
sirin k
Total 6 comments
Can you tell me how to set autocommit=0 ?
You should really pay attention to set autocommit=0 The dafault autocommit creates a transaction for each insert, with a huge overhead. Just disable it and the group insert will run more than 10 times faster.
If you want to insert many rows and you use innodb engine you should turn off checking foreign keys before start inserting and at the end turn on checking foreign keys.
This would be very useful. Thanks Sirin
Thank you very much for your useful review.Anyway im changing its title to mysql tip as you have mentioned some issues on SQL standards.also its works fine in mysql.
i have also written an article about how you can use "LOAD DATA".check here http://www.yiiframework.com/wiki/336/importing-csv-file-to-mysql-table-using-load-data-command/
Thanks,
-Sirin
The tip is partly right, but it lacks important information. I believe it should be part of a larger page.
A few remarks:
PRAGMA synchronous = OFF(beware of the side-effects).max_allowed_packetvariable that limits the size of the query one can send to the server. So grouping too many rows can lead the query to a complete failure.LOAD DATAcan also be an excellent alternative toINSERT.Leave a comment
Please login to leave your comment.