Insert into a MySQL table or update if exists
Posted by Kyle Hankinson May 1, 2023
Short answer
Give the table a primary key or unique index on the column that identifies a row, then use INSERT ... ON DUPLICATE KEY UPDATE:
-- MySQL 8.0.19 and later
INSERT INTO users (user_id, name, email)
VALUES (1, 'John Doe', 'john@example.com') AS new
ON DUPLICATE KEY UPDATE
name = new.name,
email = new.email;
If no row with user_id = 1 exists, the row is inserted. If one exists, its name and email are updated. It is one statement, so there is no gap between "check" and "write" for another connection to slip into.
On MySQL 5.7, MariaDB and MySQL 8.0 before 8.0.19, refer to the new values with VALUES():
INSERT INTO users (user_id, name, email)
VALUES (1, 'John Doe', 'john@example.com')
ON DUPLICATE KEY UPDATE
name = VALUES(name),
email = VALUES(email);
VALUES() still works on MySQL 8 but has been deprecated since 8.0.20, so prefer the AS new alias on current versions.
Insert if not exists (and do nothing otherwise)
If an existing row should be left alone, either of these works:
-- Update a column to itself: a no-op that keeps errors as errors
INSERT INTO users (user_id, name, email)
VALUES (1, 'John Doe', 'john@example.com')
ON DUPLICATE KEY UPDATE user_id = user_id;
-- Or skip the duplicate with a warning
INSERT IGNORE INTO users (user_id, name, email)
VALUES (1, 'John Doe', 'john@example.com');
Prefer the first. INSERT IGNORE turns every ignorable error into a warning, not only duplicate keys. A value too long for its column or a NULL in a NOT NULL column is silently adjusted or skipped as well.
Without a unique index, the usual fallback is INSERT ... SELECT ... WHERE NOT EXISTS (...). It works for a single connection but can still insert duplicates when two sessions run it at the same moment, so add the unique index if you can.
Update several rows at once
ON DUPLICATE KEY UPDATE works with a multi-row VALUES list, which is the fastest way to sync a batch:
INSERT INTO prices (sku, price)
VALUES ('A-100', 9.99), ('A-200', 14.50), ('A-300', 4.25) AS new
ON DUPLICATE KEY UPDATE price = new.price;
You can also compute the update from the old value, for example a counter:
INSERT INTO page_views (page, views) VALUES ('/pricing', 1)
ON DUPLICATE KEY UPDATE views = views + 1;
How to tell whether it inserted or updated
The affected-rows count tells you: 1 means a new row was inserted, 2 means an existing row was updated, and 0 means an existing row already had those exact values. (Clients connected with the CLIENT_FOUND_ROWS flag get 1 instead of 0 for that last case.)
Why not REPLACE INTO?
REPLACE INTO looks similar but deletes the existing row and inserts a new one:
REPLACE INTO users (user_id, name, email)
VALUES (1, 'John Doe', 'john@newdomain.com');
That has side effects an update does not:
- Columns you did not list are reset to their defaults, not kept.
DELETEtriggers fire, and foreign keys withON DELETE CASCADEdelete child rows.- An
AUTO_INCREMENTkey gets a new value if it was not part of the insert.
Use REPLACE only when you really want to throw the old row away.
Things that catch people out
- More than one unique index. If the new row conflicts with different existing rows on different unique indexes, MySQL updates only one of them. Upsert against a single unique key when you can.
- AUTO_INCREMENT gaps. With InnoDB's default settings, an
INSERT ... ON DUPLICATE KEY UPDATEthat ends up updating can still use up an auto-increment value, leaving gaps in the ids. That is harmless, but it surprises people who expect consecutive ids. - Other databases. The syntax is MySQL- and MariaDB-specific. PostgreSQL and SQLite use
INSERT ... ON CONFLICT ... DO UPDATE(see PostgreSQL upsert explained), and SQL Server usesMERGEor anUPDATEfollowed by anINSERTin a transaction.
Keep reading
Related guides
About the author — Kyle Hankinson is the founder and sole developer of SQLPro Studio and the Hankinsoft Development suite of database tools. He has been building native macOS and iOS applications since 2010, and now ships SQLPro on Windows and Android as well.
Try SQLPro Studio — A powerful database manager for MySQL, PostgreSQL, Microsoft SQL Server, SQLite, Oracle, and Snowflake. Available on macOS, iOS, Android, and Windows.
Download Free Trial View Pricing Compare