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.