This article is half-done without your Comment! *** Please share your thoughts via Comment ***
In this post, I am sharing a demonstration on how to skip the INSERT statement for duplicate records in MySQL.
Insert if not exists:
Basically, there are two situations for bulk insertion:
First: during insertion, if the record exists, update the old value with new the value.
This I have already posted so please visit this page.
href=”https://www.dbrnd.com/2015/08/insert-update-merge-statement-in-mysql
Second: during insertion, if the record exists, skip the new value for an insert. This I am going to explain in this post.
MySQL INSERT IGNORE statement:
Using this, you can perform actions like, “Insert if not exists”.
First, create primary data by applying proper composite unique key or primary key.
If the same key is trying to INSERT during the new insertion, INSERT IGNORE Statement only skip that transaction.
Below is a full demonstration:
I created two tables and transferring some duplicate data from one to another using INSERT IGNORE statement.
Let’s first create tables and sample data:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
CREATE TABLE tbl_First ( ID INTEGER ,Name VARCHAR(255) ); INSERT INTO tbl_First VALUES (1,'ABC'),(1,'LKM') ,(3,'PQR'),(4,'XYZ'); CREATE TABLE tbl_Second ( ID INTEGER PRIMARY KEY ,Name VARCHAR(255) ); |
We created two tables, table first has no primary key and table second has a primary key.
You can find the duplicate key in the insert statement.
Now, first try to copy this data from the table first to the second table:
1 2 |
INSERT INTO tbl_Second SELECT *FROM tbl_First; |
After executing this, You will get an error for duplicate keys.
Now, apply INSERT IGNORE Statement:
1 2 |
INSERT IGNORE INTO tbl_Second SELECT *FROM tbl_First; |
1 |
SELECT *FROM tbl_Second; |
Result is :
You can see the result where duplicate key ignored by the insert statement.