1. Home
  2. Blog
  3. Databases & SQL

Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

An upsert inserts a row if it is new and updates it if it already exists, in one statement. Learn the syntax for each database, the excluded row, and the shortcut that silently wipes your data.

9 min read
SQL upsert explained: INSERT ON CONFLICT, MERGE and the REPLACE trap

Key takeaways

  • An upsert means “insert, or update if the row already exists”.
  • It needs a primary key or unique constraint to decide what “already exists” means.
  • Inside the update, excluded refers to the row you tried to insert.
  • INSERT OR REPLACE and REPLACE INTO delete and re-insert, which can wipe other columns.

A nightly job loads stock levels from a supplier file. Some products are new, and most already exist. Checking each row with a SELECT and then choosing INSERT or UPDATE is slow and, as we will see, unsafe when two jobs run at once. An SQL upsert does both in one atomic statement.

We ran the examples in SQLite 3.50, which uses the same ON CONFLICT syntax as PostgreSQL. The outputs shown are from that run. MySQL, SQL Server and MERGE examples are shown from their documentation and were not run.

What is an upsert?

“Upsert” is a blend of update and insert. You give the database a row. If no row with the same key exists, it inserts it. If one does, it updates the existing row instead of failing. The SQL standard does not use the word, and each database spells it differently, but the idea is the same everywhere.

Why not just check first?

The obvious approach is “SELECT; if found, UPDATE, else INSERT”. It has two problems. It takes two round trips per row, and it has a race condition. If two processes check at the same moment, both see “not found”, both insert, and one fails with a duplicate key error, or worse, creates a duplicate where no constraint exists. An upsert makes the check and the write a single operation, protected by the unique constraint. Our transactions and ACID guide explains why this kind of atomicity matters.

The sample table

CREATE TABLE stock (
  sku TEXT PRIMARY KEY,
  qty INT NOT NULL,
  price INT,
  updated TEXT DEFAULT 'initial'
);
INSERT INTO stock (sku, qty, price) VALUES ('PEN', 10, 20);

A plain insert of the same SKU fails, as it should:

INSERT INTO stock (sku, qty, price) VALUES ('PEN', 5, 20);
-- UNIQUE constraint failed: stock.sku

ON CONFLICT DO UPDATE

INSERT INTO stock (sku, qty, price) VALUES ('PEN', 5, 22)
ON CONFLICT(sku) DO UPDATE SET
  qty = qty + excluded.qty,
  price = excluded.price,
  updated = 'upsert';

INSERT INTO stock (sku, qty, price) VALUES ('INK', 4, 50)
ON CONFLICT(sku) DO UPDATE SET qty = qty + excluded.qty;

-- ('INK', 4, 50, 'initial')
-- ('PEN', 15, 22, 'upsert')

PEN already existed, so the update ran: quantity went from 10 to 15 and the price changed to 22. INK was new, so it was simply inserted. excluded is a special name for “the row I tried to insert”, so excluded.qty is 5. Without the prefix, qty means the value already in the table.

The column in ON CONFLICT(sku), called the conflict target, must match a primary key or unique constraint. When we pointed it at a column without one, SQLite refused: ON CONFLICT clause does not match any PRIMARY KEY or UNIQUE constraint. PostgreSQL behaves the same way.

DO NOTHING

INSERT INTO stock (sku, qty, price) VALUES ('PEN', 99, 1)
ON CONFLICT(sku) DO NOTHING;
-- PEN unchanged: ('PEN', 15, 22, 'upsert')

DO NOTHING is “insert if new, otherwise ignore”. It is ideal for idempotent jobs, such as recording that an event was processed, where running the same import twice should not change anything. It is also how many teams load reference data safely in CI pipelines and test setups.

Conditional updates

A WHERE clause on the update decides whether the existing row should change. Here we only accept a price that is higher than the current one:

INSERT INTO stock (sku, qty, price) VALUES ('PEN', 1, 30)
ON CONFLICT(sku) DO UPDATE SET price = excluded.price
WHERE excluded.price > stock.price;    -- 30 > 22, so it updates

INSERT INTO stock (sku, qty, price) VALUES ('PEN', 1, 5)
ON CONFLICT(sku) DO UPDATE SET price = excluded.price
WHERE excluded.price > stock.price;    -- 5 is lower, so nothing changes

-- ('PEN', 15, 30, 'upsert')

This pattern is common for syncing data from several sources: only apply an incoming record if its timestamp or version is newer than the stored one. That protects you from an old, delayed message overwriting fresh data.

RETURNING

INSERT INTO stock (sku, qty, price) VALUES ('INK', 1, 50)
ON CONFLICT(sku) DO UPDATE SET qty = qty + excluded.qty
RETURNING sku, qty;
-- ('INK', 5)

RETURNING gives back the final row in the same statement, saving a follow-up SELECT. PostgreSQL and SQLite support it; SQL Server has a similar OUTPUT clause.

The REPLACE trap

SQLite’s INSERT OR REPLACE and MySQL’s REPLACE INTO look like upserts, but they are not. On a conflict they delete the old row and insert a new one. We tried it:

INSERT OR REPLACE INTO stock (sku, qty) VALUES ('PEN', 1);
-- ('PEN', 1, None, 'initial')

We only meant to change the quantity, but the price became NULL and the updated column was reset to its default, because the whole row was replaced. In a real table, that could also mean a new auto-increment ID, lost columns and, through foreign keys with ON DELETE CASCADE, deleted child rows.

There is a quieter surprise too. Our table had an audit trigger on DELETE, and it did not fire. In SQLite, delete triggers fire for REPLACE only when recursive triggers are enabled, so the audit log silently missed the deletion.

Tip: Use INSERT ... ON CONFLICT DO UPDATE (or MySQL’s ON DUPLICATE KEY UPDATE) and list exactly the columns you want to change. Avoid REPLACE unless replacing the entire row really is what you want.

Syntax by database

Database Upsert syntax Since
PostgreSQL INSERT ... ON CONFLICT (col) DO UPDATE / DO NOTHING 9.5
SQLite INSERT ... ON CONFLICT (col) DO UPDATE / DO NOTHING 3.24
MySQL / MariaDB INSERT ... ON DUPLICATE KEY UPDATE Long-standing
SQL Server MERGE 2008
Oracle MERGE 9i
PostgreSQL MERGE 15

The MySQL form looks like this (not run for this article):

INSERT INTO stock (sku, qty, price) VALUES ('PEN', 5, 22) AS new
ON DUPLICATE KEY UPDATE qty = stock.qty + new.qty, price = new.price;

Older MySQL versions use VALUES(qty) instead of a row alias. MySQL applies this to any unique key on the table, not just one you name, which can surprise you on tables with several unique indexes.

MERGE

MERGE is the SQL standard’s more general statement. It compares a source with a target and can insert, update and even delete in one go. This SQL Server example was not run for this article:

MERGE INTO stock AS t
USING (VALUES ('PEN', 5, 22)) AS s (sku, qty, price)
ON t.sku = s.sku
WHEN MATCHED THEN
  UPDATE SET qty = t.qty + s.qty, price = s.price
WHEN NOT MATCHED THEN
  INSERT (sku, qty, price) VALUES (s.sku, s.qty, s.price);

MERGE shines when syncing a whole staging table into a main table. For a single-row upsert, though, it is wordy, and SQL Server’s MERGE needs care under concurrency; Microsoft’s guidance is to use an appropriate lock hint, such as HOLDLOCK, if two sessions may merge the same keys.

Practical tips

  • Batch it. Upserting many rows in one statement or one transaction is far faster than one at a time. Our executemany test applied three rows, including a repeat of key A, and the last value for A won.
  • Index the conflict target. A unique constraint creates an index automatically, which keeps the conflict check fast. See SQL indexes explained.
  • Do not update every column blindly. Leave out created-at timestamps and IDs.
  • Watch duplicates within one statement. PostgreSQL rejects a multi-row upsert that would update the same row twice; de-duplicate the input first.
  • Test the conflict path. Run every import twice in your tests and check that the second run changes nothing it should not.

Final thoughts

Upserts replace fragile “check, then write” code with one atomic statement. Use ON CONFLICT DO UPDATE in PostgreSQL and SQLite, ON DUPLICATE KEY UPDATE in MySQL, and MERGE for larger syncs. Most importantly, update only the columns you mean to change, and stay away from REPLACE unless you truly want the whole row rebuilt.

Frequently asked questions

What is an upsert in SQL?

An upsert inserts a row if it does not exist and updates it if it does, in a single statement. It relies on a primary key or unique constraint to detect existing rows.

What does excluded mean in ON CONFLICT?

excluded refers to the row you attempted to insert. For example, excluded.qty is the new quantity, while qty alone is the value already in the table.

Is INSERT OR REPLACE the same as an upsert?

No. It deletes the existing row and inserts a new one, so columns you did not provide are reset. In our test, the price became NULL.

How do I upsert in MySQL?

Use INSERT … ON DUPLICATE KEY UPDATE, listing the columns to change. MySQL applies it when any unique key conflicts.

Should I use MERGE or ON CONFLICT?

Use ON CONFLICT for simple single-table upserts in PostgreSQL or SQLite. Use MERGE for complex syncs with inserts, updates and deletes, or in SQL Server and Oracle.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →