Xaprb

Stay curious!

3 ways to write UPSERT and MERGE queries in MySQL

with 3 comments

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.

Written by Xaprb

June 17th, 2006 at 6:52 pm

Posted in SQL

3 Responses to '3 ways to write UPSERT and MERGE queries in MySQL'

Subscribe to comments with RSS or TrackBack to '3 ways to write UPSERT and MERGE queries in MySQL'.

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

    Arjen Lentz

    9 Jul 06 at 7:12 pm

  2. 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.

    Xaprb

    9 Jul 06 at 8:42 pm

  3. 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 !!

    J Jorgenson

    12 Apr 07 at 2:23 pm

Leave a Reply