From cc2d84ac193eed5f32c1d5589ef0917ec804704e Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Tue, 27 Jun 2023 10:21:56 -0500 Subject: [PATCH] Add Ignore Duplicates When Inserting Records as a MySQL TIL --- README.md | 3 +- ...gnore-duplicates-when-inserting-records.md | 34 +++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 mysql/ignore-duplicates-when-inserting-records.md diff --git a/README.md b/README.md index 583c87e..822ad18 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1319 TILs and counting..._ +_1320 TILs and counting..._ --- @@ -554,6 +554,7 @@ _1319 TILs and counting..._ - [Display Output In A Vertical Format](mysql/display-output-in-a-vertical-format.md) - [Doing Date Math](mysql/doing-date-math.md) - [Dump A Database To A File](mysql/dump-a-database-to-a-file.md) +- [Ignore Duplicates When Inserting Records](mysql/ignore-duplicates-when-inserting-records.md) - [List Databases And Tables](mysql/list-databases-and-tables.md) - [Show Create Statement For A Table](mysql/show-create-statement-for-a-table.md) - [Show Tables That Match A Pattern](mysql/show-tables-that-match-a-pattern.md) diff --git a/mysql/ignore-duplicates-when-inserting-records.md b/mysql/ignore-duplicates-when-inserting-records.md new file mode 100644 index 0000000..c2ec536 --- /dev/null +++ b/mysql/ignore-duplicates-when-inserting-records.md @@ -0,0 +1,34 @@ +# Ignore Duplicates When Inserting Records + +While trying to run a seed script to set up some application data in a MySQL +database, I ran into several duplicate-key errors. Some of this data had +already been added in another context, but I still need some of the seeds. + +```sql +insert into MerchantAccount (col1, col2, col3) + values ('data1', 'data2', 'data3'), + ('data4', 'data5', 'data6'), + (...); +``` + +The solution was to allow MySQL to `ignore` the duplicate records and insert +the rest. + +```sql +insert ignore into MerchantAccount (col1, col2, col3) + values ('data1', 'data2', 'data3'), + ('data4', 'data5', 'data6'), + (...); +``` + +Notice all I had to do was update the statment by adding `ignore` right after +`insert.` + +> If you use the `IGNORE` modifier, ignorable errors that occur while executing +> the `INSERT` statement are ignored. For example, without `IGNORE`, a row that +> duplicates an existing `UNIQUE` index or `PRIMARY KEY` value in the table +> causes a duplicate-key error and the statement is aborted. With `IGNORE`, the +> row is discarded and no error occurs. Ignored errors generate warnings +> instead. + +[source](https://dev.mysql.com/doc/refman/8.0/en/insert.html)