|
| 1 | +# Ignore Duplicates When Inserting Records |
| 2 | + |
| 3 | +While trying to run a seed script to set up some application data in a MySQL |
| 4 | +database, I ran into several duplicate-key errors. Some of this data had |
| 5 | +already been added in another context, but I still need some of the seeds. |
| 6 | + |
| 7 | +```sql |
| 8 | +insert into MerchantAccount (col1, col2, col3) |
| 9 | + values ('data1', 'data2', 'data3'), |
| 10 | + ('data4', 'data5', 'data6'), |
| 11 | + (...); |
| 12 | +``` |
| 13 | + |
| 14 | +The solution was to allow MySQL to `ignore` the duplicate records and insert |
| 15 | +the rest. |
| 16 | + |
| 17 | +```sql |
| 18 | +insert ignore into MerchantAccount (col1, col2, col3) |
| 19 | + values ('data1', 'data2', 'data3'), |
| 20 | + ('data4', 'data5', 'data6'), |
| 21 | + (...); |
| 22 | +``` |
| 23 | + |
| 24 | +Notice all I had to do was update the statment by adding `ignore` right after |
| 25 | +`insert.` |
| 26 | + |
| 27 | +> If you use the `IGNORE` modifier, ignorable errors that occur while executing |
| 28 | +> the `INSERT` statement are ignored. For example, without `IGNORE`, a row that |
| 29 | +> duplicates an existing `UNIQUE` index or `PRIMARY KEY` value in the table |
| 30 | +> causes a duplicate-key error and the statement is aborted. With `IGNORE`, the |
| 31 | +> row is discarded and no error occurs. Ignored errors generate warnings |
| 32 | +> instead. |
| 33 | +
|
| 34 | +[source](https://dev.mysql.com/doc/refman/8.0/en/insert.html) |
0 commit comments