3 ways to write UPSERT and MERGE queries in MySQL

This article is a quick pointer on MySQL’s three techniques for UPSERT (update/insert) or MERGE queries. I’ve written about this before, but since SQL 2003 has a MERGE statement (which Oracle and DB2 support), many people are asking for similar functionality in MySQL without realizing it already exists. I hope this article helps you find what you need.

The three tools are

  1. REPLACE
  2. INSERT ... ON DUPLICATE KEY UPDATE ...
  3. Transactional UPDATE followed by INSERT

I’ve discussed them in great detail in my article on flexible insert and update statements in MySQL.

There are other methods too, such as INSERT IGNORE, but these are the three most important.

Technorati Tags:No Tags

You might also like:

  1. How to implement a queue in SQL
  2. How to write flexible INSERT and UPDATE statements in MySQL
  3. How to avoid unique index violations on updates in MySQL
  4. How to write INSERT IF NOT EXISTS queries in standard SQL
  5. A progress report on MySQL Table Sync

3 Responses to “3 ways to write UPSERT and MERGE queries in MySQL”


  1. 1 Arjen Lentz

    REPLACE does not do an update, it completely replaces the original row(s).

  2. 2 Xaprb

    After deleting them, though. So it’s actually a DELETE/INSERT construct. I didn’t mean to imply it was an UPDATE. I just wanted to list out ways to get similar functionality.

    This is great that you’re commenting, by the way. One of my goals with this blog is to learn as much as possible. Hopefully it’s also useful to others, but it’s a great chance for me to get corrections where I need them.

  3. 3 J Jorgenson

    The “INSERT .. SELECT .. ON DUPLICATE KEY” can work *MUCH* faster than a similar “INSERT … SELECT .. GROUP BY” when there is not much duplication against the Primary/Unique key on the Inserted table.

    The disk I/O is greatly increased but there are *NO* temporary tables involved greatly reducing RAM/Temp space requirements of the MySQL Server.

    In a data warehousing world, the ON DUPLICATE KEY (UPSERT) is crutial !!

Leave a Reply

Please do not use this blog to get help with problems or bugs in Maatkit or innotop: use the appropriate forums, mailing list, or bug trackers. If you're asking for help with MySQL, please use the MySQL mailing list instead.