Difficulty: Beginner
What is an UPSERT, and how do you write one in PostgreSQL and MySQL?
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.
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.
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.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.INSERT ... AS new ON DUPLICATE KEY UPDATE qty = qty + new.qty. The older VALUES(col) function is deprecated.REPLACE INTO is different: it deletes and reinserts, firing delete triggers and cascades. Avoid it for upserts.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.
SERIAL or identity value. Do not expect gap-free IDs.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.
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.
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.
UPSERT, ON CONFLICT, ON DUPLICATE KEY UPDATE, MERGE, Unique Constraint