Sub topic 16
Insert-or-update with upsert
This chapter assumes you can write INSERT, UPDATE, and DELETE statements, and that you know primary keys and UNIQUE constraints. It uses the customers table from earlier in the tutorial.
The problem upsert solves
Sometimes you have a row of data and don't know whether it is already in the table. A customer record arrives from an import, and the customer may be new or may already exist.
The naive approach is two steps: run a SELECT to check, then run an INSERT or an UPDATE. This has a race condition. Two sessions can both check, both see no row, and both try to insert. One of them then fails with a duplicate key error.
An upsert (update or insert) does the check and the write as one statement. The database decides atomically which action to take. The name is informal. Each dialect spells it differently.
PostgreSQL and SQLite: ON CONFLICT
PostgreSQL (9.5 and later) and SQLite (3.24 and later) share the same syntax.
INSERT INTO customers (id, name, email)
VALUES (1, 'Ada King', '[email protected]')
ON CONFLICT (id) DO UPDATE
SET name = EXCLUDED.name;The parts work like this:
ON CONFLICT (id)is the conflict target. It names the column or columns whose unique index or primary key decides whether a row collides.DO UPDATE SET ...runs anUPDATEon the existing row when there is a collision.EXCLUDEDis a special table name. It holds the row you tried to insert, soEXCLUDED.nameis'Ada King'.- The unqualified or table-qualified name, such as
customers.name, refers to the value already stored.
If no row with id = 1 exists, the statement behaves like a plain INSERT. If one exists, only name changes. The email and status columns keep their stored values because SET does not mention them.
Skipping duplicates with DO NOTHING
If you only want to add missing rows and leave existing ones alone, use DO NOTHING.
INSERT INTO customers (id, name, email)
VALUES (3, 'Alan Turing', '[email protected]')
ON CONFLICT DO NOTHING;Without a conflict target, DO NOTHING ignores a collision on any unique constraint. This is a common way to make an import safe to run twice.
Choosing a different conflict target
The target does not have to be the primary key. This statement matches on email:
INSERT INTO customers (id, name, email)
VALUES (10, 'Ada L.', '[email protected]')
ON CONFLICT (email) DO UPDATE
SET name = EXCLUDED.name;If a customer with that email exists, their name is updated and the new id of 10 is discarded. The target is the only collision the upsert handles. If id 10 already belonged to a different customer, the primary key violation would still raise an error.
Updating only when something changed
DO UPDATE accepts a WHERE clause. The update is skipped for rows where the condition is false.
INSERT INTO customers (id, name, email)
VALUES (1, 'Ada King', '[email protected]')
ON CONFLICT (id) DO UPDATE
SET name = EXCLUDED.name,
email = EXCLUDED.email
WHERE customers.name <> EXCLUDED.name
OR customers.email IS DISTINCT FROM EXCLUDED.email;This avoids rewriting rows that are already correct. Skipped rows are not counted as affected, and they produce no new row version in PostgreSQL. IS DISTINCT FROM is a NULL-safe comparison. PostgreSQL supports it, and SQLite supports it from version 3.39.
MySQL: ON DUPLICATE KEY UPDATE
MySQL attaches the update clause directly to the insert. It fires when the new row would violate any PRIMARY KEY or UNIQUE index. You cannot choose which one.
INSERT INTO customers (id, name, email)
VALUES (1, 'Ada King', '[email protected]') AS new
ON DUPLICATE KEY UPDATE name = new.name;The AS new row alias requires MySQL 8.0.19 or later. Older code uses name = VALUES(name). That form is deprecated but still works in many installations.
For "skip duplicates", MySQL offers INSERT IGNORE. It is blunter than DO NOTHING, because it also downgrades other errors, such as some data truncation errors, to warnings. Prefer ON DUPLICATE KEY UPDATE id = id when you only want to ignore duplicates.
Standard SQL: MERGE
MERGE is part of the SQL standard. SQL Server supports it, and PostgreSQL supports it from version 15. It joins a source of rows to the target table and applies different actions for matches and non-matches.
MERGE INTO customers AS c
USING (VALUES (1, 'Ada King', '[email protected]')) AS s (id, name, email)
ON c.id = s.id
WHEN MATCHED THEN
UPDATE SET name = s.name, email = s.email
WHEN NOT MATCHED THEN
INSERT (id, name, email) VALUES (s.id, s.name, s.email);MERGE is more verbose, but it handles cases the other forms cannot. It can use a whole table or query as the source, it can delete matched rows, and it can have several WHEN branches with extra conditions.
Dialect summary
| Dialect | Update on conflict | Ignore on conflict | Conflict detected on |
|---|---|---|---|
| PostgreSQL | `ON CONFLICT (...) DO UPDATE` | `ON CONFLICT DO NOTHING` | The named target |
| SQLite | `ON CONFLICT (...) DO UPDATE` | `ON CONFLICT DO NOTHING` | The named target |
| MySQL | `ON DUPLICATE KEY UPDATE` | `INSERT IGNORE` | Any unique index |
| SQL Server | `MERGE` | `MERGE` with no `WHEN MATCHED` branch | The `ON` condition |
Gotchas and edge cases
- Duplicates inside one statement. In PostgreSQL, a multi-row
INSERTthat contains the same key twice fails withON CONFLICT DO UPDATE command cannot affect row a second time. Remove the duplicates from the source first, for example withDISTINCT ONor aGROUP BY. In MySQL, the second row simply updates the row the first one inserted. - Affected-row counts differ. PostgreSQL counts both inserted and updated rows. MySQL reports 1 for an insert, 2 for an update that changed the row, and 0 for an update that changed nothing. Don't compare counts across dialects.
- Auto-generated keys are consumed. In PostgreSQL, a conflicting insert can still advance a sequence, so identity values may have gaps. Don't rely on them being contiguous.
- Constraints still apply.
NOT NULL,CHECK, and foreign key constraints are enforced on the inserted values and on the updated row. A conflict does not bypass them. - A target needs a matching unique index. In PostgreSQL and SQLite,
ON CONFLICT (email)fails with an error ifemailhas no unique constraint or unique index. - Overwriting with NULL.
SET email = EXCLUDED.emailreplaces a stored email with NULL if the incoming row has NULL. If that is not what you want, useSET email = COALESCE(EXCLUDED.email, customers.email).
Seeing what happened
You can combine an upsert with RETURNING in PostgreSQL and SQLite to get the final row back. RETURNING covers both the inserted and updated cases.
INSERT INTO customers (id, name, email)
VALUES (1, 'Ada King', '[email protected]')
ON CONFLICT (id) DO UPDATE
SET name = EXCLUDED.name
RETURNING id, name, status;Rows skipped by DO NOTHING or by a failed WHERE in DO UPDATE are not returned.
Choosing an approach
Use ON CONFLICT or ON DUPLICATE KEY UPDATE for the common case of one key and one row, or a batch of rows. Use MERGE when you need to combine inserts, updates, and deletes from a full source table, and when you accept its extra care around concurrency. Run any bulk upsert inside a transaction, as covered earlier, so a failure leaves the table unchanged.
Exercise
A PostgreSQL table customers has id as primary key and a UNIQUE constraint on email. You run INSERT INTO customers (id, name, email) VALUES (5, 'New Name', '[email protected]') ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name;, and Ada's row (id 1) already has that email. What happens, and how would you change the statement so the existing Ada row is updated instead?
Show answer
The statement fails with a unique violation on email. No row with id 5 exists, so there is no conflict on the named target id, and the insert proceeds. It then collides with Ada's row on email, which ON CONFLICT (id) does not handle. To update Ada's row, change the target to ON CONFLICT (email) DO UPDATE SET name = EXCLUDED.name.
Exercise
Write a PostgreSQL statement that inserts customer 7, named 'Katherine Johnson' with email '[email protected]', but does nothing if a customer with id 7 or that email already exists.
Show answer
INSERT INTO customers (id, name, email) VALUES (7, 'Katherine Johnson', '[email protected]') ON CONFLICT DO NOTHING; Without a conflict target, DO NOTHING covers collisions on any unique constraint, including the primary key and the email.