Inserting multiple rows

suggest change
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 INSERT statement.

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.

Ignoring existing rows

When importing large data sets, you may want to skip rows that would fail a constraint, for example a duplicate primary key. INSERT IGNORE does that.

Consider following example database:

SELECT * FROM `people`;

Result:

+----+------+
| 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`;

Result:

+----+--------+
| id |  name  |
+----+--------+
|  1 |  john  |
|  2 |  anna  |
|  3 |  mike  |
+----+--------+

INSERT IGNORE also hides other errors. Invalid values are adjusted to the nearest legal value and the statement continues with a warning, instead of aborting. Duplicate-key rows are skipped. Do not use it when you need those errors.

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');

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents