INSERT INTO `my_table` (`field_1`, `field_2`) VALUES ('data_1', 'data_2'), ('data_1', 'data_3'), ('data_4', 'data_5');
This is an easy way to add several rows at once with one
This kind of 'batch' insert is much faster than inserting rows one by one. Typically, inserting 100 rows in a single batch insert this way is 10 times as fast as inserting them all individually.
When importing large datasets, it may be preferable under certain circumstances to skip rows that would usually cause the query to fail due to a column restraint e.g. duplicate primary keys. This can be done using
Consider following example database:
SELECT * FROM `people`; --- Produces: +----+------+ | id | name | +----+------+ | 1 | john | | 2 | anna | +----+------+ INSERT IGNORE INTO `people` (`id`, `name`) VALUES ('2', 'anna'), --- Without the IGNORE keyword, this record would produce an error ('3', 'mike'); SELECT * FROM `people`; --- Produces: +----+--------+ | id | name | +----+--------+ | 1 | john | | 2 | anna | | 3 | mike | +----+--------+
The important thing to remember is that INSERT IGNORE will also silently skip other errors too, here is what Mysql official documentations says:
Data conversions that would trigger errors abort the statement if IGNORE is not > specified. With IGNORE, invalid values are adjusted to the closest values and >inserted; warnings are produced but the statement does not abort.
Note :- The section below is added for the sake of completeness, but is not considered best practice (this would fail, for example, if another column was added into the table).
If you specify the value of the corresponding column for all columns in the table, you can ignore the column list in the
INSERT statement as follows:
INSERT INTO `my_table` VALUES ('data_1', 'data_2'), ('data_1', 'data_3'), ('data_4', 'data_5');