Upsert MySQL rows using a deliberate unique key

MySQL's INSERT ... ON DUPLICATE KEY UPDATE reacts to a conflict with a primary or unique key. It does not search for an arbitrary row matching whichever columns happen to look similar. Define the identity in the schema, then state which values an incoming row is allowed to replace.

This example identifies inventory by Code. An incoming quantity is a replacement count, not an increment. That distinction matters when a request is retried, because replacing a value and adding the same value twice have different effects.

Create an isolated fixture

Use MySQL 8.4, a selected scratch database and a fresh connection with default autocommit behavior and no open transaction. The connection needs permission to create temporary tables. This fixture explicitly uses InnoDB so its data changes can be rolled back.

SQL
CREATE TEMPORARY TABLE UpsertDemo (
    Code varchar(20) PRIMARY KEY,
    Quantity int NOT NULL
) ENGINE = InnoDB;

INSERT INTO UpsertDemo (Code, Quantity)
VALUES ('BOLT', 5), ('RIVET', 7);

Only this session can see the temporary table. Do not replace its name with a production table while learning the statement. The initial insert establishes a small known baseline before the demonstration transaction begins.

Name the incoming row

SQL
START TRANSACTION;

INSERT INTO UpsertDemo (Code, Quantity)
VALUES ('BOLT', 9), ('NUT', 3) AS incoming
ON DUPLICATE KEY UPDATE
    Quantity = incoming.Quantity;

SELECT Code, Quantity FROM UpsertDemo ORDER BY Code;

ROLLBACK;
SELECT Code, Quantity FROM UpsertDemo ORDER BY Code;
DROP TEMPORARY TABLE UpsertDemo;

The first result is BOLT / 9, NUT / 3 and RIVET / 7. BOLT conflicts with the existing primary key, so its quantity changes. NUT is inserted. RIVET remains unchanged because no incoming row names it.

After rollback, the second result is the original BOLT / 5 and RIVET / 7. The explicit drop removes the temporary table. MySQL temporary-table creation itself is not undone by rollback, even though it does not cause the usual implicit commit of ordinary table DDL. If a statement fails interactively, stop and roll back before continuing.

Prefer aliases over deprecated incoming-value syntax

The alias follows the complete VALUES list and gives the update expression access to the proposed row. The alias must differ from the table name. This is the current form documented for MySQL 8.4.

Older examples use VALUES(Quantity) inside the update clause. That incoming-value function is deprecated in MySQL. This does not deprecate the VALUES keyword that introduces the insert rows. Do not assume a MySQL example also works unchanged in MariaDB or PostgreSQL, which have their own syntax and compatibility rules.

Keep identity unambiguous

Any applicable unique constraint can trigger the update. If a table has several unique keys and an incoming row conflicts with different existing rows, the operation is not an instruction to reconcile all of them. Review that schema and conflict policy rather than assuming the primary key always decides the target.

A nullable unique column may also admit cases that do not behave like an ordinary non-null identity. This fixture uses a non-null primary key to avoid that ambiguity. Collation rules still affect whether textual codes compare as the same key.

Define retries and results

Replaying this replacement operation with the same input leaves the same quantities, provided no other actor changes them between requests. That observation is not a complete distributed idempotency guarantee. An incrementing update needs a different retry policy, and concurrent writers still need an application-level consistency contract.

Do not equate affected-row count with the number of business records accepted. MySQL distinguishes inserted, changed and unchanged rows, and client connection flags can alter the count reported for unchanged data. Verify the resulting values when they determine subsequent behavior.

In application code, bind the row values through the driver. Avoid a separate “check then insert” race, and do not add IGNORE merely to suppress unexpected constraint errors. An error can reveal an invalid batch that should be corrected rather than partially accepted.

Source and further reading

This article addresses the problem raised by Keshan in “Insert into a MySQL table or update if exists” on Stack Overflow, licensed under CC BY-SA 4.0 . The question is the topic source. The explanations and examples here are newly authored from the database documentation, rather than reproduced from a community answer.

MySQL :: MySQL 8.4 Reference Manual :: 15.2.7.2 INSERT ... ON DUPLICATE KEY UPDATE Statement
https://dev.mysql.com/doc/refman/8.4/en/insert-on-duplicate.html
MySQL :: MySQL 8.4 Reference Manual :: 15.3.3 Statements That Cause an Implicit Commit
https://dev.mysql.com/doc/refman/8.4/en/implicit-commit.html
MySQL :: MySQL 8.4 Reference Manual :: 15.1.20.2 CREATE TEMPORARY TABLE Statement
https://dev.mysql.com/doc/refman/8.4/en/create-temporary-table.html

Author: Herman Schoenfeld