Planet PostgreSQL·· 3d agoFeatured
PostgreSQL 19 Developer Guide: Returning Existing Rows with INSERT ON CONFLICT DO SELECT
Deepak Mahto: Exploring PostgreSQL 19: A Developer’s Guide to New Features – Part 1: INSERT ON CONFLICT DO SELECT
Brief · Based on the source excerpt
PostgreSQL 19’s INSERT … ON CONFLICT DO SELECT returns the existing row on a unique key conflict. A registration example shows why DO NOTHING RETURNING yields no row on conflict and why DO UPDATE returns one only by rewriting it.
Why It Matters
For get or create operations keyed by a unique value, returning the existing row on conflict avoids both an extra database round trip and a rewrite just to retrieve the row.
Technical Breakdown · Distilled from the original source
Getting or creating a user by unique email
- The
app_usersexample defines its primary key withid bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEYand its required, unique email withemail text NOT NULL UNIQUE. It also includesfull_nameand acreated_atcolumn that defaults tonow(). The example inserts a record, then attempts another insert with the same email and a different name. - The application wants the row that exists, whether the current statement inserts it or it was already in the table. The same requirement applies to finding or creating a tag and resolving a customer reference from an upstream feed.
What each conflict action returns
- In the example,
ON CONFLICT (email) DO NOTHING RETURNING id, email, full_nameproduces(0 rows). The conflict causes the insert to skip the row, so the empty result does not mean the email is absent. Issuing a separateSELECTcosts another database round trip, and the row can change or disappear between the two statements. - The excerpt also starts a single statement CTE workaround, placing the insert and its
RETURNINGresult ininsand combining queries withUNION ALL.DO UPDATEcan return the existing row but rewrites it in the process. PostgreSQL 19’sDO SELECTreturns that row on conflict without an update.
Source: Planet PostgreSQL· postgr.es
PG Radar summarizes verified changes and impact. Read the original post for full technical details and code samples.