The Insert on Duplicate Key Update statement is the extension of the INSERT statement in MySQL. When we specify the ON DUPLICATE KEY UPDATE clause in a SQL statement and a row would cause duplicate error value in a UNIQUE or PRIMARY KEY index column, then updation of the existing row occurs.
The INSERT IGNORE command keeps the first set of the duplicated records and discards the remaining. The REPLACE command keeps the last set of duplicates and erases out any earlier ones. Another way to enforce uniqueness is to add a UNIQUE index rather than a PRIMARY KEY to a table.
ON DUPLICATE KEY UPDATE is a MariaDB/MySQL extension to the INSERT statement that, if it finds a duplicate unique or primary key, will instead perform an UPDATE. The row/s affected value is reported as 1 if a row is inserted, and 2 if a row is updated, unless the API's CLIENT_FOUND_ROWS flag is set.
You can use INSERT... IGNORE syntax if you want to take no action when there's a duplicate record. You can use REPLACE INTO syntax if you want to overwrite an old record with a new one with the same key.
Yes, use INSERT ... ON DUPLICATE KEY UPDATE id=id
(it won't trigger row update even though id
is assigned to itself).
If you don't care about errors (conversion errors, foreign key errors) and autoincrement field exhaustion (it's incremented even if the row is not inserted due to duplicate key), then use INSERT IGNORE
like this:
INSERT IGNORE INTO <table_name> (...) VALUES (...)
REPLACE INTO
pros:
cons:
too slow.
auto-increment key will CHANGE(increase by 1) if there is entry matches unique key
or primary key
, because it deletes the old entry then insert new one.
INSERT IGNORE
pros:
cons:
auto-increment key will not change if there is entry matches unique key
or primary key
but auto-increment index will increase by 1
some other errors/warnings will be ignored such as data conversion error.
INSERT ... ON DUPLICATE KEY UPDATE
pros:
cons:
looks relatively complex if you just want to insert not update.
auto-increment key will not change if there is entry matches unique key
or primary key
but auto-increment index will increase by 1
unique key
or primary key
?As mentioned in the comment below by @toien: "auto-increment column will be effected depends on innodb_autoinc_lock_mode
config after version 5.1" if you are using innodb
as your engine, but this also effects concurrency, so it needs to be well considered before used. So far I'm not seeing any better solution.
Use ON DUPLICATE KEY UPDATE ...
,
Negative : because the UPDATE
uses resources for the second action.
Use INSERT IGNORE ...
,
Negative : MySQL will not show any errors if something goes wrong, so you cannot handle the errors. Use it only if you don’t care about the query.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With