Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing multiple insert queries

Tags:

sql

mysql

I am about to insert 365 insert records, I want to know which would be better.

1) Inserting 1000 insert queries one by one (for every record)

2) Insert like

insert into table name ('field1', 'field2') values (value,value),(value,value),(value,value),(value,value)

I want to does the second one perform faster and will it be useful.

like image 601
raju Avatar asked Aug 14 '26 17:08

raju


1 Answers

According to MySQL INSERT plan we have following issues with time to spend on:

- Connecting
- Sending query to server
- Parsing query 
- Inserting row (1 × size of row)
- Inserting indexes: (1 × number of indexes)
- Closing

Due to this, multiple insert is much more faster since it will produce Connecting, Sending query to server, Parsing query, Closing overheads only once. And this is shown in manual too:

  • If you are inserting many rows from the same client at the same time, use INSERT statements with multiple VALUES lists to insert several rows at a time. This is considerably faster (many times faster in some cases) than using separate single-row INSERT statements. If you are adding data to a nonempty table, you can tune the bulk_insert_buffer_size variable to make data insertion even faster. See Section 5.1.4, “Server System Variables”.
like image 64
Alma Do Avatar answered Aug 17 '26 07:08

Alma Do