SQL | INSERT IGNORE Statement
We know that a primary key of a table cannot be duplicated. For instance, the roll number of a student in the student table must always be distinct. Similarly, the EmployeeID is expected to be unique in an employee table. When we try to insert a tuple into a table where the primary key is repeated, it results in an error. However, with the INSERT IGNORE statement, we can prevent such errors from popping up, especially when inserting entries in bulk and such errors can interrupt the flow of insertion. Instead, only a warning is generated.
Cases where INSERT IGNORE avoids error
- Upon insertion of a duplicate key where the column must contain a PRIMARY KEY or UNIQUE constraint
- Upon insertion of NULL value where the column has a NOT NULL constraint.
- Upon insertion of a row to a partitioned table where the inserted values go against the partition format.
Say we have a relation, Employee.
As we can notice, the entries are not sorted on the basis of their primary key, i.e. EmployeeID.
INSERT IGNORE INTO Employee (EmployeeID, Name, City) VALUES (15002, 'Ram', 'Mumbai');
No entry inserted.
Inserting multiple records
When inserting multiple records at once, any that cannot be inserting will not be, but any that can will be:
INSERT IGNORE INTO Employee (EmployeeID, Name, City) VALUES (15007, 'Shikha', 'Delhi'), (15002, 'Ram', 'Mumbai'), (15009, 'Sam', 'Ahmedabad');
The first and the last entries get inserted; the middle entry is simple ignored. No error is flashed.
Most users do not prefer INSERT IGNORE over INSERT since some errors may slip unnoticed. This may cause inconsistencies in the table, thereby causing some tuples to not get inserted without the user having a chance to correct them. Hence, INSERT IGNORE must be used in very specific conditions.
This article is contributed by Anannya Uberoi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.