Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

InnoDB: Bulk insert using transaction OR combine multiple queries?

Tags:

mysql

When doing a bulk INSERT in InnoDB, should I use a transaction

START TRANSACTION;
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3);
INSERT INTO tbl_name (a,b,c) VALUES(4,5,6);
INSERT INTO tbl_name (a,b,c) VALUES(7,8,9);
COMMIT TRANSACTION;

Or combine multiple queries?

INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);

If it matters, I'm using PHP and the MySQL database is on the same machine.

like image 563
Code Avatar asked Dec 24 '15 04:12

Code


1 Answers

I'd recommend combining multiple queries like you have in the bottom example.

INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);

If either of the value-pair fails, none of the data will be inserted. This method also sends less characters and round-trip to the DB. The implication of less characters may not be that attractive but it still holds slight advantage.

EDIT:

Tim has a great question. Let me include information from MySQL doc

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.

like image 145
zedfoxus Avatar answered Oct 12 '22 23:10

zedfoxus