← Lessons

quiz vs the machine

Gold1340

Databases

Upsert and On Conflict

Insert if new, update if it already exists, in one statement.

4 min read · core · beat Gold to climb

Insert or Update

An upsert inserts a row, but if a row with the same key already exists it updates that row instead. Doing this in one statement avoids a race where two clients both check, both find nothing, and both insert.

How It Works

The engine attempts the insert and detects a conflict on a unique or primary key constraint. On conflict it runs the update branch you defined. In SQL this often reads as insert with an on conflict clause that names the conflicting column and an update action.

Why It Helps

  • It is atomic, so concurrent writers cannot create duplicates.
  • It removes a network round trip compared with check then insert.
  • You can choose to do nothing on conflict to make inserts idempotent.

A correct upsert needs a unique constraint to detect the conflict; without one the database has no way to know a row is a duplicate.

Key idea

An upsert combines insert and update into one atomic statement that resolves on a unique constraint, preventing duplicate rows under concurrency.

Check yourself

Answer to earn rating on the learn ladder.

1. What does an upsert do on a key conflict?

2. What does an upsert require to detect a conflict?