Read time: ~8 minutes
PostgreSQL 19 finally lets
INSERThand back the row that already exists, no dummy update, no exception block, no second round trip.
PostgreSQL 19 was released on November 19, 2026. With it, I’m starting a new series: what’s new in PostgreSQL 19 primarily for application developers, the people writing SQL and PL/pgSQL every day, or supporting migrations to PostgreSQL.
Part 1 starts with the feature that removes a workaround almost every code base carries: INSERT … ON CONFLICT DO SELECT.
The Pattern Every Application Writes
Every application has a get-or-create:
- Register a user by email
- Find or create a tag
- Resolve a customer reference arriving from an upstream feed
The ask is always the same. Give me the row — whether it was already there or not.
Until PostgreSQL 19, INSERT … ON CONFLICT couldn’t say that. DO NOTHING skips the row and returns nothing. DO UPDATE returns the row, but only by writing it again.
Before PostgreSQL 19: Three Workarounds, Three Compromises
Let’s create a sample table:
CREATE TABLE app_users ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, email text NOT NULL UNIQUE, full_name text, created_at timestamptz NOT NULL DEFAULT now());INSERT INTO app_users (email, full_name)VALUES ('deepak@dcg.com', 'Deepak Mahto');
Workaround 1: DO NOTHING, then SELECT
postgres=# INSERT INTO app_users (email, full_name) VALUES ('deepak@dcg.com', 'Deepak M') ON CONFLICT (email) DO NOTHING RETURNING id, email, full_name; id | email | full_name----+-------+-----------(0 rows)INSERT 0 0 The row exists. RETURNING gives you nothing. So the application fires a second SELECT as two round trips, and a window between them where the row can change or disappear.
The one-statement version wraps it in a CTE:
WITH ins AS ( INSERT INTO app_users (email, full_name) VALUES ('deepak@dcg.com', 'Deepak M') ON CONFLICT (email) DO NOTHING RETURNING id, email, full_name)SELECT id, email, full_name FROM insUNION ALLSELECT id, email, full_name FROM app_usersWHERE email = 'deepak@dcg.com' AND NOT EXISTS (SELECT 1 FROM ins); Looks perfect, right? Under READ COMMITTED, the outer SELECT reads from the statement’s snapshot. If another session inserts the same email and commits after our statement starts, DO NOTHING sees the conflict but the SELECT doesn’t see the row. Zero rows back. Rare, and almost impossible to reproduce in testing.
Workaround 2: The “Dummy” DO UPDATE
The popular fix is to update the row to itself, so RETURNING has something to return:
postgres=# SELECT ctid, xmin, id, email, full_name FROM app_users; ctid | xmin | id | email | full_name-------+------+----+--------------------+-------------- (0,1) | 732 | 1 | deepak@dcg.com | Deepak Mahto(1 row)postgres=# INSERT INTO app_users (email, full_name) VALUES ('deepak@dcg.com', 'Deepak M') ON CONFLICT (email) DO UPDATE SET email = EXCLUDED.email RETURNING id, email, full_name, (xmax = 0) AS inserted; id | email | full_name | inserted----+--------------------+--------------+---------- 1 | deepak@dcg.com | Deepak Mahto | f(1 row)INSERT 0 1postgres=# SELECT ctid, xmin, id, email, full_name FROM app_users; ctid | xmin | id | email | full_name-------+------+----+--------------------+-------------- (0,2) | 733 | 1 | deepak@dcg.com | Deepak Mahto(1 row)postgres=# SELECT n_tup_ins, n_tup_upd, n_dead_tup FROM pg_stat_user_tables WHERE relname = 'app_users'; n_tup_ins | n_tup_upd | n_dead_tup-----------+-----------+------------ 1 | 1 | 1(1 row) Nothing changed. PostgreSQL still wrote a new row version — new ctid, new xmin, one dead tuple. At scale that is:
- A dead tuple per lookup, and vacuum debt that grows with traffic
- WAL for every “read”, shipped to replicas and backups
- A row lock taken on every call
UPDATEtriggers firing for a change that never happened – audit rows,updated_atstamps- Phantom
UPDATEevents in logical replication and CDC
Workaround 3: The Exception Block (Straight from Oracle)
This is the one I see in converted Oracle code. The PL/SQL source:
BEGIN INSERT INTO app_users (email, full_name) VALUES (p_email, p_name) RETURNING id INTO v_id;EXCEPTION WHEN DUP_VAL_ON_INDEX THEN SELECT id INTO v_id FROM app_users WHERE email = p_email;END; It usually lands in PostgreSQL almost 1:1, with WHEN unique_violation. It works. But every EXCEPTION block runs as a subtransaction, and every duplicate leaves an aborted row behind.
We called that converted function 1,000 times for an email that already exists:
postgres=# SELECT n_tup_ins, n_dead_tup, pg_size_pretty(pg_relation_size('app_users')) AS heap_size FROM pg_stat_user_tables WHERE relname = 'app_users'; n_tup_ins | n_dead_tup | heap_size-----------+------------+----------- 1001 | 1000 | 72 kB(1 row) One live row. A thousand dead ones. Functionally correct. Physically expensive.
Outputs above are from previous PostgreSQL versions (<19), the “before” behaviour.

PostgreSQL 19: ON CONFLICT DO SELECT
PostgreSQL 19 adds a third conflict action. From the INSERT docs:
INSERT INTO table_name [ AS alias ] [ ( column_name [, ...] ) ] ... ON CONFLICT conflict_target DO SELECT [ FOR { UPDATE | NO KEY UPDATE | SHARE | KEY SHARE } ] [ WHERE condition ] RETURNING ... On conflict, the existing row is returned — not modified. No conflict, the row is inserted and returned. One statement, atomic. The docs call it what it is: idempotent insert, or get or create.
The rules worth knowing before you use it:
RETURNINGis mandatory. Leave it out and you getERROR: ON CONFLICT DO SELECT requires a RETURNING clause.- A conflict target is mandatory.
ON CONFLICT (email) DO SELECT— unlikeDO NOTHING, you must name the arbiter. - No lock by default. Add
FOR UPDATE,FOR NO KEY UPDATE,FOR SHAREorFOR KEY SHAREto lock the returned row. WHEREfilters what comes back. It runs after the conflict is found. The existing row is the table name or alias, the proposed row isEXCLUDED. If the condition is false, the row is not returned — but it is still locked whenFOR UPDATE/SHAREis used.- Arbiters: unique indexes and
NOT DEFERRABLEconstraints only. Exclusion constraints are not supported. - Privileges:
SELECTon the table. WithFOR UPDATE/SHARE, alsoUPDATEon at least one column. - Command tag:
INSERT 0 n, wherencounts rows inserted or selected for return.

Side by side with the two actions we already had:

Let’s See It in Action
Same table recreated, same existing user. This time with DO SELECT:
postgres=# INSERT INTO app_users (email, full_name) VALUES ('deepak@dcg.com', 'Deepak M') ON CONFLICT (email) DO SELECT RETURNING id, email, full_name; id | email | full_name----+--------------------+-------------- 1 | deepak@dcg.com | Deepak Mahto(1 row)INSERT 0 1 The existing row comes back as it is in the table — Deepak Mahto, not the Deepak M we proposed. Nothing was written.
Proof — the row version didn’t move:
SELECT ctid, xmin FROM app_users WHERE email = 'deepak@dcg.com';-- same ctid and xmin as before the current INSERT SELECT n_tup_upd, n_dead_tup FROM pg_stat_user_tablesWHERE relname = 'app_users';-- n_tup_upd = 0, n_dead_tup = 0 A new email takes the insert path and comes back the same way:
INSERT INTO app_users (email, full_name)VALUES ('asmita@dcg.com', 'Asmita')ON CONFLICT (email) DO SELECTRETURNING id, email, full_name;┌────┬────────────────┬───────────┐│ id │ email │ full_name │├────┼────────────────┼───────────┤│ 3 │ asmita@dcg.com │ Asmita │└────┴────────────────┴───────────┘INSERT 0 1 Was It Inserted or Fetched?
Applications often need to know which path ran. For example, send the welcome email only for new users. For example. The old trick was RETURNING (xmax = 0) AS inserted on a dummy DO UPDATE.
PostgreSQL 18 added OLD and NEW to RETURNING. The PostgreSQL 19 docs spell out how they behave with DO SELECT: on the select path, old holds the existing row and new is identical to it. On the insert path, old is NULL. So:
INSERT INTO app_users (email, full_name)VALUES ('deepak@dcg.com', 'Deepak M')ON CONFLICT (email) DO SELECTRETURNING id, email, (old.id IS NULL) AS inserted;-- inserted = f for an existing email, t for a new one ┌────┬────────────────┬──────────┐│ id │ email │ inserted │├────┼────────────────┼──────────┤│ 1 │ deepak@dcg.com │ f │└────┴────────────────┴──────────┘ No system columns. No guessing.
Forgot RETURNING?
postgres=# INSERT INTO app_users (email) VALUES ('deepak@dcg.com') ON CONFLICT (email) DO SELECT; ERROR: ON CONFLICT DO SELECT requires a RETURNING clause That’s not a bug. That’s PostgreSQL making you say what you want back.
Why This Matters More Than It Looks
DO SELECT uses the same speculative insertion as DO NOTHING and DO UPDATE. Two sessions racing on the same email will not hit a unique_violation — one inserts, the other gets the row back. What it drops is the write:
- No new row version, so no dead tuple and no vacuum debt
- No row write on the lookup path (a FOR UPDATE lock aside)
- No
UPDATEtriggers firing for a change that never happened - No phantom
UPDATEevents in logical replication or CDC
When You Need the Lock: FOR UPDATE
Plain DO SELECT takes no row lock. The row you got back can change a millisecond later. If the very next statement modifies it, lock it in the same call:
BEGIN;INSERT INTO wallets (user_id, balance)VALUES (42, 0)ON CONFLICT (user_id) DO SELECT FOR UPDATERETURNING id, balance;-- the wallet row is now ours until COMMITUPDATE wallets SET balance = balance - 100 WHERE user_id = 42;COMMIT; Get-or-create and lock, in one round trip. Pick the weakest lock that does the job: FOR NO KEY UPDATE if you won’t touch the key, FOR SHARE if you only need the row to stay put.
What It Costs (or Saves)
Remember Workaround 3? 1,000 calls of the converted Oracle function, for an email that already exists, left 1,000 dead tuples behind. Here is the same test with the DO SELECT version of that function (shown in the next section), on PostgreSQL 19:

Same result for the caller. No sub-transactions, no dead rows, no vacuum work left behind.
One honest note: if almost every call finds an existing row, a plain SELECT first is still the cheapest lookup. But you then need extra code to handle two sessions inserting the same key at once. DO SELECT gives you get-or-create in one statement that’s safe under concurrency.
PL/pgSQL: Get-or-Create in One Statement
Here is the converted Oracle function from Workaround 3, rewritten for PostgreSQL 19:
CREATE OR REPLACE FUNCTION get_or_create_user(p_email text, p_name text)RETURNS bigintLANGUAGE plpgsqlAS $$DECLARE v_id bigint;BEGIN INSERT INTO app_users (email, full_name) VALUES (p_email, p_name) ON CONFLICT (email) DO SELECT RETURNING id INTO v_id; RETURN v_id;END;$$; No EXCEPTION block, so no sub-transaction. No aborted row per duplicate. No second SELECT.
Migration Angle: What to Look For in Converted Code
If you are moving from Oracle or SQL Server, these are the patterns DO SELECT replaces:
| Source pattern | Typical PostgreSQL conversion before 19 | The problem | PostgreSQL 19 |
|---|---|---|---|
Oracle: INSERT … EXCEPTION WHEN DUP_VAL_ON_INDEX THEN SELECT | EXCEPTION WHEN unique_violation | Subtransaction and dead tuple per duplicate | ON CONFLICT (key) DO SELECT RETURNING … INTO |
SELECT, then INSERT if not found | Same two statements | Race: concurrent callers hit unique_violation | DO SELECT |
SQL Server: IF NOT EXISTS (…) INSERT …; SELECT … | Same, or DO NOTHING + SELECT | Several statements, race window between check and insert. | DO SELECT |
MERGE … WHEN NOT MATCHED THEN INSERT, then SELECT | MERGE + SELECT | Concurrent inserts of the same key can still raise unique_violation. The MERGE docs recommend ON CONFLICT … DO SELECT instead. | DO SELECT |
Any of the above, already ported as a dummy DO UPDATE | SET col = EXCLUDED.col | New row version on every lookup | DO SELECT |
The two docs pages point at each other. ON CONFLICT calls MERGE the more standard option. MERGE recommends INSERT … ON CONFLICT to return the existing row (with DO SELECT) if a concurrent INSERT occurs. For get-or-create, that settles it.
Couple of Things to Remember
1. Sequence values still get burned. The identity default is evaluated before the conflict check. On PostgreSQL 16, four conflicting attempts on one email, then a brand-new user:
postgres=# INSERT INTO app_users (email, full_name) VALUES ('krish@dcg.com', 'Krishna') RETURNING id, email; id | email----+------------------ 6 | krish@dcg.com(1 row) Id 6, not 2. DO SELECT goes down the same insert path first, so expect the same gaps. If your application assumes gapless ids, it was already wrong.
2. BEFORE INSERT triggers still fire on conflict. They run for the proposed row before the conflict is detected. On PostgreSQL 16, DO NOTHING fires the BEFORE INSERT trigger; DO UPDATE fires BEFORE INSERT and BEFORE UPDATE. With DO SELECT, the UPDATE trigger goes away; the INSERT one doesn’t. Keep BEFORE INSERT triggers free of side effects.
3. You get the stored row, not your input. DO SELECT returns what is in the table. If the existing row should be refreshed with the new values, that is still DO UPDATE, and that one should write.
4. WHERE + FOR UPDATE locks more than it returns. Rows that fail the WHERE condition are not returned, but they are still locked.
Key Takeaways
DO SELECTfor get-or-create — when you need the row back and nothing should change
DO NOTHINGwhen you don’t need the row back
DO UPDATEonly when the existing row should actually change
Retire the dummy SET col = EXCLUDED.col
Retire EXCEPTION WHEN unique_violationget-or-create blocks in converted Oracle code- Use
RETURNING (old.id IS NULL) AS insertedto know which path ran
The Bottom Line
For years, getting a row back from INSERT meant writing it again. PostgreSQL 19 lets get-or-create be what it always was; an insert when it’s new, a read when it isn’t.
Next in the series: PL/pgSQL’s SELECT expression INTO variable — the same code, up to 5x faster on PostgreSQL 19.
References
- PostgreSQL 19 Released! — postgresql.org
- INSERT — PostgreSQL 19 documentation
- MERGE — PostgreSQL 19 documentation
- PostgreSQL 19 Release Notes


