Skip to content

Commit cc2d84a

Browse files
committed
Add Ignore Duplicates When Inserting Records as a MySQL TIL
1 parent c185ac1 commit cc2d84a

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
1212

13-
_1319 TILs and counting..._
13+
_1320 TILs and counting..._
1414

1515
---
1616

@@ -554,6 +554,7 @@ _1319 TILs and counting..._
554554
- [Display Output In A Vertical Format](mysql/display-output-in-a-vertical-format.md)
555555
- [Doing Date Math](mysql/doing-date-math.md)
556556
- [Dump A Database To A File](mysql/dump-a-database-to-a-file.md)
557+
- [Ignore Duplicates When Inserting Records](mysql/ignore-duplicates-when-inserting-records.md)
557558
- [List Databases And Tables](mysql/list-databases-and-tables.md)
558559
- [Show Create Statement For A Table](mysql/show-create-statement-for-a-table.md)
559560
- [Show Tables That Match A Pattern](mysql/show-tables-that-match-a-pattern.md)
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
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

Comments
 (0)