Skip to content
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_users example defines its primary key with id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY and its required, unique email with email text NOT NULL UNIQUE. It also includes full_name and a created_at column that defaults to now(). 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_name produces (0 rows). The conflict causes the insert to skip the row, so the empty result does not mean the email is absent. Issuing a separate SELECT costs 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 RETURNING result in ins and combining queries with UNION ALL. DO UPDATE can return the existing row but rewrites it in the process. PostgreSQL 19’s DO SELECT returns 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.

Read Official Source

Related PostgreSQL Reference