Nov 23, 20267 min read

Postgres Upsert with INSERT ON CONFLICT

How INSERT ... ON CONFLICT works in Postgres, when to use DO NOTHING or DO UPDATE, how it compares to MERGE, and how to tell inserts from updates with RETURNING.

Illustration for Postgres Upsert with INSERT ON CONFLICT

An upsert writes a row if its key is new and updates it if the key already exists, which is what you want for syncing products from a supplier feed, storing the latest device status or making a create endpoint safe to retry.

Postgres has done this atomically since 9.5 with INSERT ... ON CONFLICT, and recent releases added ways to see exactly what the statement did, which used to need workarounds.

At a glance

ON CONFLICT DO NOTHINGON CONFLICT DO UPDATEMERGE
What happens on an existing keyRow is skippedExisting row is updatedWhatever the matching WHEN clause says
Needs a unique index or constraintYesor none for any conflictYesNo
Safe against a concurrent insert of the same keyYesYesCan raise a unique violation
Returns the row on conflictNoYesthe updated rowYesfrom Postgres 17
Available since9.59.515

How does INSERT ON CONFLICT work?

Postgres tries the insert first and takes the conflict action instead when the row would violate the unique index named in the conflict target, and the INSERT documentation guarantees an atomic insert-or-update outcome even when another transaction inserts the same key at the same moment.

CREATE TABLE products ( sku text PRIMARY KEY, name text NOT NULL, price_cents bigint NOT NULL, updated_at timestamptz NOT NULL DEFAULT now() ); INSERT INTO products (sku, name, price_cents) VALUES ('SKU-1001', 'Steel water bottle', 2400) ON CONFLICT (sku) DO UPDATE SET name = EXCLUDED.name, price_cents = EXCLUDED.price_cents, updated_at = now() RETURNING sku, price_cents;

EXCLUDED is the row you tried to insert, and the target table's own columns refer to the existing row, so products.price_cents is the old price and EXCLUDED.price_cents the new one. The conflict target (sku) must match a unique index or constraint exactly, including any WHERE predicate on a partial unique index, or Postgres rejects the statement with "there is no unique or exclusion constraint matching the ON CONFLICT specification".

When should you use DO NOTHING?

DO NOTHING fits writes where the first one wins and later duplicates should be ignored, such as recording a processed webhook ID or a message key in an idempotency table. It returns no row for the skipped insert, so code that needs the existing row has to select it in a second query, or use DO SELECT on Postgres 19, which the Postgres 19 release notes describe as returning the conflicting row and optionally locking it.

Leaving out the conflict target (ON CONFLICT DO NOTHING) skips the row on a conflict with any unique constraint, which is convenient and also hides mistakes, so name the column unless you mean every constraint.

Updating only when something changed

A WHERE clause on the update turns a blind overwrite into a conditional one. Two common uses are skipping no-op writes, which saves WAL and dead tuples on tables that are synced often, and refusing out-of-order updates when events can arrive late:

INSERT INTO products (sku, name, price_cents, updated_at) VALUES ('SKU-1001', 'Steel water bottle', 2200, '2026-11-23T10:00:00Z') ON CONFLICT (sku) DO UPDATE SET name = EXCLUDED.name, price_cents = EXCLUDED.price_cents, updated_at = EXCLUDED.updated_at WHERE products.updated_at < EXCLUDED.updated_at AND (products.name, products.price_cents) IS DISTINCT FROM (EXCLUDED.name, EXCLUDED.price_cents);

When the WHERE is false, the row is left alone and RETURNING returns nothing for it, which tells the caller the update was stale or identical.

Batch upserts

Upserting many rows in one statement is much faster than a loop of single-row statements, and unnest keeps it to one round trip with array parameters. Each key may appear only once per statement, because Postgres refuses to update the same row twice in one command with "ON CONFLICT DO UPDATE command cannot affect row a second time", so deduplicate the batch in the application first.

INSERT INTO products (sku, name, price_cents) SELECT * FROM unnest($1::text[], $2::text[], $3::bigint[]) ON CONFLICT (sku) DO UPDATE SET name = EXCLUDED.name, price_cents = EXCLUDED.price_cents, updated_at = now();

Was it an insert or an update?

Before Postgres 18 the usual answer was a second query or a trick with system columns. Postgres 18 added OLD and NEW to RETURNING, as listed in the Postgres 18 release notes, and OLD columns are null when the row was inserted:

INSERT INTO products (sku, name, price_cents) VALUES ('SKU-1001', 'Steel water bottle', 2400) ON CONFLICT (sku) DO UPDATE SET price_cents = EXCLUDED.price_cents RETURNING new.sku, (old.sku IS NULL) AS inserted, old.price_cents AS previous_price;

INSERT ON CONFLICT vs MERGE

MERGE joins a source against the target and runs different actions for matched and unmatched rows, including deletes, which suits a nightly sync from a staging table. The MERGE documentation points out that under concurrent inserts it follows the normal isolation rules and can fail where INSERT ... ON CONFLICT would update, so for an API endpoint keyed on a unique column, ON CONFLICT is the safer choice.

Best fit: ON CONFLICT DO UPDATE for request-time upserts, DO NOTHING for first-write-wins idempotency, MERGE for batch syncs that also delete.

Upserts in Encore

Encore

Encore is a backend framework with built-in infrastructure, and a service's Postgres database, its migrations and the endpoints that write to it sit in the same package, so the unique constraint the upsert depends on is declared right next to the query that relies on it. This catalog service exposes a sync endpoint that a supplier feed can call as often as it likes:

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

-- catalog/migrations/1_create_products.up.sql CREATE TABLE products ( sku text PRIMARY KEY, name text NOT NULL, price_cents bigint NOT NULL, updated_at timestamptz NOT NULL );
// catalog/catalog.go package catalog import ( "context" "errors" "time" "encore.dev/storage/sqldb" ) var db = sqldb.NewDatabase("catalog", sqldb.DatabaseConfig{Migrations: "./migrations"}) type UpsertParams struct { SKU string `json:"sku"` Name string `json:"name"` PriceCents int64 `json:"price_cents"` UpdatedAt time.Time `json:"updated_at"` } type UpsertResult struct { Changed bool `json:"changed"` } // Upsert stores the product, ignoring stale or identical updates. // //encore:api private method=PUT path=/products/:sku func Upsert(ctx context.Context, sku string, p *UpsertParams) (*UpsertResult, error) { var got string err := db.QueryRow(ctx, ` INSERT INTO products (sku, name, price_cents, updated_at) VALUES ($1, $2, $3, $4) ON CONFLICT (sku) DO UPDATE SET name = EXCLUDED.name, price_cents = EXCLUDED.price_cents, updated_at = EXCLUDED.updated_at WHERE products.updated_at < EXCLUDED.updated_at AND (products.name, products.price_cents) IS DISTINCT FROM (EXCLUDED.name, EXCLUDED.price_cents) RETURNING sku `, sku, p.Name, p.PriceCents, p.UpdatedAt).Scan(&got) if errors.Is(err, sqldb.ErrNoRows) { return &UpsertResult{Changed: false}, nil } if err != nil { return nil, err } return &UpsertResult{Changed: true}, nil }

encore run starts Postgres locally and applies the migration, so you can call the endpoint twice with the same body and watch the second call return changed: false in the local trace, and an integration test can assert the same against a test database. The databases docs cover the query API and migrations, and when you deploy, the same database is provisioned on RDS or Cloud SQL in your AWS or GCP account, as described in the AWS infrastructure docs.

The endpoint is private, so only other services in the app can call it, and a supplier import service can publish rows over Pub/Sub and call catalog.Upsert from a subscriber without exposing the write path. A coding agent adding another synced table can follow the same pattern in one change, migration and endpoint together, and test it against the local database before anything is deployed.

Best fit: sync and ingest endpoints that need to be safe to retry and cheap to call with unchanged data.

Common upsert mistakes

  • No unique index on the conflict column. The statement fails at parse time, so the fix is a migration, not a code change.
  • Overwriting columns the caller did not send. List only the columns the source owns in SET, otherwise a partial update from one system wipes fields another system wrote.
  • Assuming sequences stay gap-free. An ON CONFLICT that updates still consumes a value from an identity column's sequence, so IDs on upserted tables skip numbers.
  • Duplicate keys in one batch. Deduplicate before the statement, keeping the newest version of each key.

Frequently asked questions

How do I upsert a row in Postgres?

Use INSERT ... ON CONFLICT (column) DO UPDATE SET col = EXCLUDED.col. The conflict target must match a unique index or constraint, and EXCLUDED holds the row you tried to insert, so the update can copy its values into the existing row.

What is the difference between ON CONFLICT DO NOTHING and DO UPDATE?

DO NOTHING skips the insert when the key already exists and returns no row for it. DO UPDATE changes the existing row instead, and RETURNING then returns that updated row, which is what most sync and idempotent write paths want.

Should I use MERGE or INSERT ON CONFLICT for upserts?

Use INSERT ON CONFLICT for single-table upserts keyed on a unique constraint, because it handles a concurrent insert of the same key by updating instead of failing. MERGE fits multi-branch syncs from a source table, such as insert, update and delete in one statement, but under concurrency it can still raise a unique violation.

How do I write an upsert in an Encore service?

Declare the unique constraint in the service's migration, then run INSERT ... ON CONFLICT ... DO UPDATE with db.QueryRow and scan the RETURNING columns. The same SQL runs on the local Postgres that encore run starts and on RDS or Cloud SQL in your account.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders