Skip to content
select * from depesz;·· 19h ago

How PostgreSQL 19 Handles INSERT … ON CONFLICT DO SELECT

Missed in PostgreSQL 19 : Add support for INSERT … ON CONFLICT DO SELECT.

Key Takeaway

PostgreSQL 19’s INSERT … ON CONFLICT DO SELECT inserts new rows or returns existing ones on conflict without a no-op update. It requires RETURNING and supports optional row locking. When locking is requested, conflicting rows filtered out by WHERE are still locked.

Why It Matters

When replacing no-op updates in get-or-create code, check whether the old primary key is null to identify inserts, since the command tag counts returned rows.

Technical Breakdown · Distilled from the original source

Get or create in one statement

  • ON CONFLICT DO NOTHING RETURNING * returns no existing row on conflict. With DO SELECT, nonconflicting rows are inserted normally and existing rows can be returned directly, without a separate SELECT. Omitting RETURNING raises an error.
  • In the example, using DO UPDATE to assign the same username still changes ctid and xmin, generates a dead tuple for VACUUM, writes WAL, and fires update triggers. With DO SELECT, the existing row keeps its ctid and xmin.

Distinguish inserts from existing rows

  • A batch can produce the command tag INSERT 0 2 even when only one row was inserted, because the tag counts returned rows. PostgreSQL 18 added old and new in RETURNING; the example uses old.id is null as was_inserted to distinguish the outcomes because id is a non-null primary key.
  • Conflicting insert attempts still consume identity sequence values, so IDs can have gaps.

Filter and lock conflicting rows

  • WHERE filters existing rows returned on conflict, not newly inserted rows. In the example, WHERE users.id < 3 excludes the existing row with id = 5 but still returns the newly inserted row with id = 14.
  • FOR UPDATE, FOR NO KEY UPDATE, FOR SHARE, and FOR KEY SHARE can lock conflicting rows. When a locking clause is used, conflicting rows excluded by WHERE are still locked.
Source: select * from depesz;· depesz.com

PG Radar summarizes verified changes and impact. Read the original post for full technical details and code samples.

Read Official Source

Related PostgreSQL Reference