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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With