For the complete documentation index, see llms.txt. This page is also available as Markdown.

INSERT ON DUPLICATE KEY UPDATE

Complete guide to inserting data in MariaDB. Complete INSERT syntax for single rows, bulk operations, and ON DUPLICATE KEY handling for production use.

Syntax

INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
  [INTO] tbl_name [PARTITION (partition_list)] [(col,...)]
  {VALUES | VALUE} ({expr | DEFAULT},...),(...),...
  [ ON DUPLICATE KEY UPDATE
    col=expr
      [, col=expr] ... ]
Railroad diagram of INSERT ... ON DUPLICATE KEY UPDATE — equivalent to the BNF above
Railroad diagram of value_list

Or:

Or:

Description

INSERT ... ON DUPLICATE KEY UPDATE (often called "upsert") 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.

If more than one unique index is matched, only the first is updated. It is not recommended to use this statement on tables with more than one unique index.

If the table has an AUTO_INCREMENT primary key and the statement inserts a new row, the LAST_INSERT_ID() function returns the AUTO_INCREMENT value of that newly inserted row. It is not affected when the statement updates an existing row instead.

The VALUES() function can only be used in a ON DUPLICATE KEY UPDATE clause and has no meaning in any other context. It returns the column values from the INSERT portion of the statement. This function is particularly useful for multi-rows inserts.

The DELAYED option is ignored when you use ON DUPLICATE KEY UPDATE.

See Partition Pruning and Selection for details on the PARTITION clause.

This statement activates INSERT and UPDATE triggers. See Trigger Overview for details.

See also a similar statement, REPLACE.

Examples

If there is no existing key, the statement runs as a regular INSERT:

A regular INSERT with a primary key value of 1 will fail, due to the existing key:

However, we can use an INSERT ON DUPLICATE KEY UPDATE instead:

Note that there are two rows reported as affected, but this refers only to the UPDATE.

Adding a second unique column:

Where two rows match the unique keys match, only the first is updated. This can be unsafe and is not recommended unless you are certain what you are doing.

Although the third row with an id of 3 has an id2 of 13, which also matched, it was not updated.

Changing id to an auto_increment field. If a new row is added, the auto_increment is moved forward. If the row is updated, it remains the same.

Referring to column values from the INSERT portion of the statement:

See the VALUES() function for more.

See Also

This page is licensed: CC BY-SA / Gnu FDL

spinner

Last updated

Was this helpful?