Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use always INSERT ....ON DUPLICATE UPDATE for simple updates/inserts?

Tags:

sql

mysql

(MYSQL) Is there any significant performance differences, or other reasons not to use the INSERT ... ON DUPLICATE UPDATE sql to update by PK/insert new stuff?

like image 495
Itay Moav -Malimovka Avatar asked Jun 01 '26 21:06

Itay Moav -Malimovka


1 Answers

No, there is none.

INSERT ON DUPLICATE KEY UPDATE will locate the record and update it just as a simple UPDATE would do.

In fact this is just a UPDATE, followed by an INSERT should the UPDATE fail.

INSERT ON DUPLICATE KEY UPDATE can be a faster alternative to a grouped update (when you have a source table with multiple records per key and want to increment the target table once per record).

If there are few values per key, this query:

INSERT
INTO    t_target
SELECT  target, cnt
FROM    t_sparse d
ON DUPLICATE KEY UPDATE
        t_target.cnt = t_target.cnt + d.cnt

will be more efficient than this one:

INSERT
INTO    t_target
SELECT  target, cnt
FROM    (
        SELECT  target, SUM(cnt) AS cnt
        FROM    t_sparse di
        GROUP BY
                target
        ) d
ON DUPLICATE KEY UPDATE
        t_target.cnt = t_target.cnt + d.cnt

See this article in my blog for more detail:

  • Efficient INSERT ON DUPLICATE KEY UPDATE
like image 106
Quassnoi Avatar answered Jun 03 '26 12:06

Quassnoi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!