UPSERT is a SQL operation that inserts a missing row or updates an existing one, decided by a unique key in a single atomic statement. The name blends UPDATE and INSERT, and the pattern is known under dialect-specific syntax such as INSERT ON CONFLICT in PostgreSQL and SQLite, INSERT … ON DUPLICATE KEY UPDATE in MySQL and MariaDB, and the standard MERGE statement.
In relational databases, an UPSERT replaces the fragile application pattern of reading a row first and then choosing between INSERT and UPDATE. Because the database resolves the decision against a unique constraint or primary key, the operation stays correct under concurrent writers, which makes it a core tool for synchronization jobs, counters, caches and idempotent data loading.
How an UPSERT resolves a key conflict
An UPSERT works by attempting an insert and treating a unique key violation as a signal rather than an error. The engine checks the conflict target, usually a primary key or a unique index, and if a matching row exists it applies the update branch to that row instead of failing the statement.
In PostgreSQL the statement reads INSERT INTO stock (sku, qty) VALUES ('A1', 5) ON CONFLICT (sku) DO UPDATE SET qty = stock.qty + EXCLUDED.qty. The special EXCLUDED pseudo-table holds the values that the insert would have written, so the update can combine old and new data. The alternative DO NOTHING clause simply skips conflicting rows, which is useful for deduplicating inserts.
The key requirement is that the conflict target is backed by a unique index or constraint. Without one the engine has no reliable way to detect a duplicate, and most dialects reject the statement outright. The steps below summarize what happens for each proposed row.
- The engine probes the unique index for the conflict key.
- If no row matches, it performs a normal insert and fires insert triggers.
- If a row matches, it locks that row and evaluates the optional WHERE condition of the update branch.
- It applies the update, or skips the row for DO NOTHING, and records the outcome in the affected row count.
UPSERT syntax across database systems
There is no single UPSERT keyword in the SQL standard, so every major engine exposes the operation through its own syntax. The closest standard construct is MERGE, defined in SQL:2003, which matches a source against a target and branches on WHEN MATCHED and WHEN NOT MATCHED.
The table below compares the most common dialects and the conflict mechanism each one relies on.
| Engine | Syntax | Conflict detection | Notes |
|---|---|---|---|
| PostgreSQL | INSERT … ON CONFLICT DO UPDATE | Named columns or constraint | Available since version 9.5 |
| SQLite | INSERT … ON CONFLICT DO UPDATE | Named unique columns | Adopted PostgreSQL-style syntax in 3.24 |
| MySQL and MariaDB | INSERT … ON DUPLICATE KEY UPDATE | Any unique index on the table | Ambiguous when several unique keys exist |
| Microsoft SQL Server | MERGE | Join condition in ON clause | Needs locking hints for safe concurrency |
| Oracle Database | MERGE | Join condition in ON clause | Mature support with DELETE branch |
| PostgreSQL 15 and later | MERGE | Join condition in ON clause | Not a full replacement for ON CONFLICT |
MySQL also offers REPLACE INTO, which looks similar but deletes the old row and inserts a new one. That behavior resets columns that were not supplied, fires delete triggers and can break foreign key relationships, so it is not a true UPSERT.
UPSERT compared with INSERT, UPDATE and MERGE
UPSERT differs from its neighbors in who decides the branch and when. A plain INSERT fails on a duplicate key, a plain UPDATE silently affects zero rows when nothing matches, and an UPSERT folds both outcomes into one statement that the database evaluates row by row.
| Statement | Row missing | Row present | Typical use |
|---|---|---|---|
| INSERT | Creates the row | Raises a duplicate key error | New records with guaranteed uniqueness |
| UPDATE | Affects zero rows | Modifies the row | Changes to known existing records |
| UPSERT | Creates the row | Modifies or skips the row | Synchronization and idempotent writes |
| MERGE | Inserts per WHEN NOT MATCHED | Updates or deletes per WHEN MATCHED | Bulk reconciliation of two data sets |
| REPLACE INTO | Creates the row | Deletes and recreates the row | Legacy MySQL code, best avoided |
MERGE is more expressive because it can delete rows and join arbitrary sources, but in several engines it was not designed for high-concurrency single-row writes. ON CONFLICT is usually the safer choice for online transactional traffic, while MERGE suits batch reconciliation in data warehouses.
Concurrency and atomicity guarantees
The main reason to use an UPSERT is atomic conflict handling under concurrency. The application pattern of SELECT followed by INSERT contains a race window: two sessions can both see that a row is missing, both insert it, and one of them fails or creates a duplicate if no constraint exists.
PostgreSQL guarantees that INSERT ON CONFLICT DO UPDATE yields either an insert or an update for each proposed row, even at the READ COMMITTED isolation level, without requiring retries. MySQL achieves similar behavior through next-key locking on the unique index. SQL Server MERGE, by contrast, can still produce key violations under load unless the target is read with HOLDLOCK or SERIALIZABLE hints.
Several engine-level details affect performance and correctness, as the following table shows.
| Behavior | Where it occurs | Practical consequence |
|---|---|---|
| Sequence values consumed | PostgreSQL, MySQL auto-increment | Gaps appear in identity columns after conflicts |
| Row locked on conflict | Most engines | Hot keys serialize writers and raise contention |
| Same row twice in one statement | PostgreSQL ON CONFLICT | Statement fails with a cardinality error |
| Deadlocks on unique index | MySQL under heavy parallel load | Retry logic is still advisable |
| Race in MERGE | SQL Server without hints | Duplicate key errors despite the MERGE |
When to use an UPSERT and how to write it well
An UPSERT is the right tool when the same logical record may arrive more than once and the latest or combined value should win. Typical cases include idempotent event ingestion, replication into a reporting copy, user preference storage and running counters keyed by date or identifier.
| Situation | Recommended form | Reason |
|---|---|---|
| Duplicate events must be ignored | ON CONFLICT DO NOTHING | Keeps the first write and avoids extra locking |
| Latest value should win | DO UPDATE SET col = EXCLUDED.col | Overwrites stale data in one step |
| Values must accumulate | DO UPDATE SET n = t.n + EXCLUDED.n | Atomic increment without a read |
| Out-of-order updates possible | DO UPDATE … WHERE t.version < EXCLUDED.version | Rejects older data arriving late |
| Large batch reconciliation | MERGE or staging table plus UPSERT | Processes sets efficiently |
Good practice is to name the conflict target explicitly, list only the columns that should change, and add a version or timestamp guard when messages may arrive out of order. Using RETURNING in PostgreSQL, or checking the affected row count in MySQL, tells the application whether the row was created or modified.
Common mistakes and limitations
Most UPSERT bugs come from a mismatch between the conflict key and the real business key. If the unique constraint is missing or covers the wrong columns, the statement either fails or quietly inserts duplicates.
- Missing unique index: the conflict clause has nothing to detect, so duplicates accumulate or the statement is rejected.
- Several unique keys in MySQL: ON DUPLICATE KEY UPDATE may update a row matched by an unexpected key.
- Overwriting every column: an unconditional update can erase values set by other processes.
- Ignoring triggers: insert and update triggers fire differently, so auditing logic must handle both paths.
- Assuming MERGE is concurrency-safe: in some engines it needs explicit locking to avoid duplicate key errors.
UPSERT also does not replace transaction design. It makes one row change atomic, but multi-row business rules still require explicit transactions, appropriate isolation levels and, under heavy contention, retry handling for deadlocks.
Put simply
An UPSERT is an instruction that says: add this record, or update it if it is already there. Think of a guest list at an event. When a name arrives, the organizer either writes a new line or corrects the existing line for that person, and never ends up with the same guest listed twice.
The database makes this decision itself, in one step, using a unique identifier such as a customer number. That matters because many programs may write at the same moment, and the database is the only party that can check and change the list without anyone slipping in between.
In practice
An online retailer receives stock updates from three warehouses through a message queue. Each message carries a product code, a warehouse code, a quantity and a version number, and the queue may deliver the same message twice or out of order. The inventory table has a unique constraint on product code and warehouse code.
The ingestion service writes every message with a PostgreSQL INSERT ON CONFLICT statement that targets those two columns and updates quantity and version only when the incoming version is higher. Duplicate messages change nothing, late messages are rejected by the version guard, and new products appear automatically on first arrival.
After the switch from a read-then-write approach, the team removed a nightly deduplication job, and duplicate inventory rows stopped appearing even during peak sales when about 2,000 updates per second arrive across 12 parallel consumers.