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. WithDO SELECT, nonconflicting rows are inserted normally and existing rows can be returned directly, without a separateSELECT. OmittingRETURNINGraises an error.- In the example, using
DO UPDATEto assign the same username still changesctidandxmin, generates a dead tuple forVACUUM, writes WAL, and fires update triggers. WithDO SELECT, the existing row keeps itsctidandxmin.
Distinguish inserts from existing rows
- A batch can produce the command tag
INSERT 0 2even when only one row was inserted, because the tag counts returned rows. PostgreSQL 18 addedoldandnewinRETURNING; the example usesold.id is null as was_insertedto distinguish the outcomes becauseidis a non-null primary key. - Conflicting insert attempts still consume identity sequence values, so IDs can have gaps.
Filter and lock conflicting rows
WHEREfilters existing rows returned on conflict, not newly inserted rows. In the example,WHERE users.id < 3excludes the existing row withid = 5but still returns the newly inserted row withid = 14.FOR UPDATE,FOR NO KEY UPDATE,FOR SHARE, andFOR KEY SHAREcan lock conflicting rows. When a locking clause is used, conflicting rows excluded byWHEREare 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.