While executing an INSERT
statement with many rows, I want to skip duplicate entries that would otherwise cause failure. After some research, my options appear
Adding to this. If you use both INSERT IGNORE
and ON DUPLICATE KEY UPDATE
in the same statement, the update will still happen if the insert finds a duplicate key. In other words, the update takes precedence over the ignore. However, if the ON DUPLICATE KEY UPDATE
clause itself causes a duplicate key error, that error will be ignored.
This can happen if you have more than one unique key, or if your update attempts to violate a foreign key constraint.
CREATE TABLE test
(id BIGINT (20) UNSIGNED AUTO_INCREMENT,
str VARCHAR(20),
PRIMARY KEY(id),
UNIQUE(str));
INSERT INTO test (str) VALUES('A'),('B');
/* duplicate key error caused not by the insert,
but by the update: */
INSERT INTO test (str) VALUES('B')
ON DUPLICATE KEY UPDATE str='A';
/* duplicate key error is suppressed */
INSERT IGNORE INTO test (str) VALUES('B')
ON DUPLICATE KEY UPDATE str='A';