UPSERT

Difficulty: Beginner

Question

What is an UPSERT, and how do you write one in PostgreSQL and MySQL?

Answer

An UPSERT is a single atomic statement that inserts a row, or updates the existing row if inserting would violate a unique key. In PostgreSQL it is INSERT ... ON CONFLICT (...) DO UPDATE, and in MySQL it is INSERT ... ON DUPLICATE KEY UPDATE. It replaces the race-prone "SELECT, then INSERT or UPDATE" pattern in application code.

Why not check first, then insert?

The naive approach is two steps: SELECT to see if the row exists, then INSERT or UPDATE. Two concurrent requests can both see "no row" and both insert, causing a duplicate key error or duplicate data. An UPSERT relies on a unique index to detect the conflict inside the database, so it is atomic and safe under concurrency.

PostgreSQL: ON CONFLICT

  • Available since PostgreSQL 9.5.
  • The conflict target, such as ON CONFLICT (user_id, product_id) or ON CONFLICT ON CONSTRAINT name, must match a unique index or constraint.
  • EXCLUDED refers to the row you tried to insert: SET qty = cart.qty + EXCLUDED.qty.
  • DO NOTHING silently skips conflicting rows, which is handy for idempotent ingestion.
  • A WHERE clause on DO UPDATE can skip pointless updates, for example only when the incoming timestamp is newer.
  • RETURNING gives back inserted or updated rows. With DO NOTHING, skipped rows are not returned.

MySQL: ON DUPLICATE KEY UPDATE

  • Fires on a conflict with the primary key or any unique index, so with several unique indexes it can update a row you did not expect.
  • Since MySQL 8.0.19 you can alias the new row, INSERT ... AS new ON DUPLICATE KEY UPDATE qty = qty + new.qty. The older VALUES(col) function is deprecated.
  • Affected-rows count is 1 for an insert and 2 for an update of an existing row.
  • REPLACE INTO is different: it deletes and reinserts, firing delete triggers and cascades. Avoid it for upserts.

MERGE (SQL standard)

PostgreSQL 15 added MERGE (and PostgreSQL 17 added RETURNING to it). SQL Server and Oracle have had it for years. It is great for syncing a staging table into a target with matched and not-matched branches. However, in PostgreSQL MERGE does not give the same concurrency guarantee as ON CONFLICT; concurrent inserts can still raise a unique violation. For single-row upserts under concurrency, prefer ON CONFLICT.

Gotchas

  • Sequence gaps: a conflicting insert still consumes a SERIAL or identity value. Do not expect gap-free IDs.
  • Same key twice in one statement: PostgreSQL raises "ON CONFLICT DO UPDATE command cannot affect row a second time". Deduplicate the input first.
  • No unique index, no upsert: without one, the statement just inserts duplicates (MySQL) or errors on the conflict target (PostgreSQL).
  • Upserts that always update create dead tuples and WAL even when nothing changed; use the WHERE filter to avoid no-op writes.

A typical real use: storing payment status from webhooks keyed by payment_id, where the same event may arrive twice.

How INSERT ... ON CONFLICT decides. The unique index, not application code, decides whether the row is inserted or updated.
  1. INSERT proposed row: Values arrive from the application.
  2. Check unique index: Look up the conflict target key.
  3. No match: insert: Row is added like a normal INSERT.
  4. Match: DO UPDATE or NOTHING: Existing row updated using EXCLUDED values.
  5. RETURNING result: Inserted or updated row sent back.

Code examples

PostgreSQL: add to cart with ON CONFLICT

CREATE TABLE cart_items (
  user_id    BIGINT  NOT NULL,
  product_id BIGINT  NOT NULL,
  qty        INTEGER NOT NULL CHECK (qty > 0),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  PRIMARY KEY (user_id, product_id)
);

INSERT INTO cart_items (user_id, product_id, qty)
VALUES (42, 1001, 2)
ON CONFLICT (user_id, product_id)
DO UPDATE SET qty        = cart_items.qty + EXCLUDED.qty,
              updated_at = now()
RETURNING user_id, product_id, qty;

Running the same statement again returns qty 4, because the conflict on the primary key triggers the update branch.

MySQL 8: row alias syntax

INSERT INTO cart_items (user_id, product_id, qty)
VALUES (42, 1001, 2) AS new
ON DUPLICATE KEY UPDATE
  qty = cart_items.qty + new.qty;

-- Idempotent webhook ingestion in PostgreSQL: ignore duplicates
-- INSERT INTO payment_events (event_id, payload) VALUES ($1, $2)
-- ON CONFLICT (event_id) DO NOTHING;

The AS new alias replaces the deprecated VALUES() function in MySQL 8.0.19 and later.

Key points

  • UPSERT = insert, or update on unique-key conflict, in one atomic statement.
  • PostgreSQL: INSERT ... ON CONFLICT (target) DO UPDATE / DO NOTHING, with EXCLUDED for new values.
  • MySQL: INSERT ... ON DUPLICATE KEY UPDATE; use the row alias instead of VALUES() in 8.0.19+.
  • An upsert requires a unique index or constraint to detect conflicts.
  • Avoid REPLACE INTO in MySQL; it deletes and reinserts the row.

Common follow-up questions

  • Why is SELECT-then-INSERT unsafe under concurrency?
  • How is MERGE different from ON CONFLICT in PostgreSQL?
  • How would you upsert 10,000 rows in a single statement?
  • Why do IDs have gaps after many upserts?

Interview tips

  • Lead with the race condition upserts solve; it shows you understand why the feature exists.
  • Write the PostgreSQL syntax from memory, including EXCLUDED; this is often asked as a live coding question.
  • Mention idempotent webhook or event ingestion with DO NOTHING as a real use case.

Concepts covered

UPSERT, ON CONFLICT, ON DUPLICATE KEY UPDATE, MERGE, Unique Constraint

More Database Design questions