If you build a feature that attaches tags to posts, this requirement always shows up. A user types accessibility. If that tag already exists, use its id. If not, create it and use the new id. Because you get it if it’s there and create it if it isn’t, the pattern is called get-or-create.
The usual implementation goes like this: look it up with SELECT, and if there’s no row, INSERT. It works fine when you test it alone. But when two requests try to create the same tag at nearly the same moment, one of them fails with this error.
ERROR: duplicate key value violates unique constraint "tags_name_key"
DETAIL: Key (name)=(race6) already exists.PostgreSQL 19, released on November 19, 2026, added syntax that finishes this pattern in one query: INSERT ... ON CONFLICT DO SELECT. I ran it on PostgreSQL 19.0 and put numbers on how it differs from the workarounds we’ve been using. Every output in this post was run and pasted from the official Docker image (postgres:19).

Photo by Nathan Dumlao on Unsplash
Why is get-or-create tricky? It breaks under concurrent requests#
The example is a single tags table. Tag names must be unique, so name has a UNIQUE constraint.
CREATE TABLE tags (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL UNIQUE
);
INSERT INTO tags (name) VALUES ('a11y');The most common implementation asks twice from application code.
SELECT id FROM tags WHERE name = 'wcag'; -- 1. check if it exists
INSERT INTO tags (name) VALUES ('wcag') RETURNING id; -- 2. create it if notThe problem is the gap between step 1 and step 2. If two requests run step 1 at the same moment, both get “not found” and both go on to step 2. Only the one that arrives first succeeds, and the other gets a duplicate key error. When the order of execution overlaps and the result changes, that’s called a race condition. When you’re developing alone, requests never overlap, so this is the perfect setup for a bug that ends in “works on my machine.”
It isn’t hard to reproduce. Open two terminals. In A, open a transaction, run only the INSERT, and hold off on committing. While that’s pending, try get-or-create with the same name in B.

In the same situation, session B gets a different result depending on the approach (measured on PostgreSQL 19.0)
Two workarounds we used up to PostgreSQL 18#
PostgreSQL has had INSERT ... ON CONFLICT since 9.5. It lets you say “if this INSERT hits a unique constraint, do something else instead of raising an error.” People usually call it upsert. There were two actions to choose from: DO NOTHING, which does nothing, and DO UPDATE, which modifies the existing row.
What get-or-create needs, “just give me the existing row,” wasn’t there. Adding RETURNING to DO NOTHING doesn’t return the conflicting row either, because RETURNING only returns rows that the statement actually inserted. So workarounds appeared.
Overwriting with the same value via DO UPDATE: writing just to read#
The widely used one is a meaningless modification with DO UPDATE. If you overwrite a row with the same value, it counts as an “updated row,” so RETURNING hands it back.
INSERT INTO tags (name) VALUES ('a11y')
ON CONFLICT (name) DO UPDATE SET name = EXCLUDED.name
RETURNING id, name;EXCLUDED is the name for the row you tried to insert and that conflicted. The id comes back fine. But even with an identical value, PostgreSQL really does rewrite that row. You can see it by printing the row’s internal info before and after.
SELECT id, name, xmin, ctid FROM tags WHERE name = 'a11y';-- Before DO UPDATE
id | name | xmin | ctid
----+------+------+-------
1 | a11y | 675 | (0,1)
-- After DO UPDATE
id | name | xmin | ctid
----+------+------+-------
1 | a11y | 676 | (0,2)xmin is the id of the transaction that created the row, and ctid is where the row physically sits. Both changed. The content is the same, but a new version of the row was created. It’s like taking the milk out of the fridge just to check that it’s there, then putting the same milk back. The milk is unchanged, but you open the fridge door every single time.

Photo by Debby Hudson on Unsplash
Since the row is actually written, UPDATE triggers (functions the database runs automatically when a row changes) fire too. On a table with a trigger that counts modifications, I ran this workaround twice and the count went up to 2. I only read the row, yet it became a row that had been “updated twice.” If the table stamps updated_at automatically, the modification time changes as well.
CTE with UNION ALL: concurrent requests can get an empty result#
The approach that came along to avoid the write is a CTE. A CTE (the WITH clause) is a way to put a small named query inside a query. You try the insert with DO NOTHING, and if it didn’t go in, you look the row up with SELECT in the same statement.
WITH ins AS (
INSERT INTO tags (name) VALUES ('a11y')
ON CONFLICT (name) DO NOTHING
RETURNING id, name
)
SELECT id, name FROM ins
UNION ALL
SELECT id, name FROM tags WHERE name = 'a11y'
LIMIT 1;Run alone, it works and there’s no write. But when you overlap two sessions as in the diagram above, the result looks like this.
id | name
----+------
(0 rows)It’s an empty result with no error. Why empty? Under PostgreSQL’s default setting (READ COMMITTED), a single statement reads tables through a snapshot taken when it starts, a picture of the data at that moment. Session B’s INSERT waits on A at the unique index, sees the conflict, and backs off. But the SELECT that follows is looking at the picture from when the statement started, so A’s row, committed after that, is invisible to it. It couldn’t insert it and it couldn’t find it.
To prevent this, you have to write your own code that retries when the result is empty. Up to PostgreSQL 18, it was one of two things: accept the write, or hand-write the retry.
ON CONFLICT DO SELECT: how to use it#
PostgreSQL 19 added DO SELECT as a third action for ON CONFLICT. On a conflict, it returns the existing row as it is, without modifying it.
INSERT INTO tags (name) VALUES ('a11y')
ON CONFLICT (name) DO SELECT
RETURNING id, name; id | name
----+------
1 | a11y
(1 row)If you print xmin and ctid again before and after, they’re still 676 and (0,2). The row wasn’t touched. On the table with the trigger, the modification count didn’t go up either. And if you insert a name that doesn’t exist, it creates a new row like a normal INSERT.
There are two rules to follow. You must write RETURNING and the conflict target (the (name) in ON CONFLICT (name)). If you leave them out, you get a requires a RETURNING clause or requires inference specification or constraint name error, respectively.
On PostgreSQL 18 and earlier, this statement fails with
syntax error at or near "SELECT"(checked on 18.7). Managed services tend to adopt new major versions late, so check your version first withSELECT version();.
Telling a newly created row from one that already existed#
Sometimes you need to know whether the row was just created or already there, say to send a notification only when it’s new. Use old in RETURNING. old refers to the row as it was before this statement ran, and it arrived in PostgreSQL 18. A newly inserted row has no “before,” so every value in old is NULL.
INSERT INTO tags (name) VALUES ('wcag')
ON CONFLICT (name) DO SELECT
RETURNING id, name, (old.id IS NULL) AS created;-- A name that already exists
id | name | created
----+------+---------
6 | wcag | f
-- A name inserted for the first time
id | name | created
----+------+---------
8 | aria | tUnder concurrent requests, it waits and returns the existing row#
This is the real result of the diagram at the top. Session A inserts a new tag inside a transaction and commits 3 seconds later. In the meantime, session B comes in with the same name.
| Session B’s approach | What B got after session A committed |
|---|---|
SELECT then INSERT | duplicate key error |
CTE + UNION ALL | 0 rows (no error) |
DO UPDATE workaround | 1 existing row (the row is rewritten) |
DO SELECT | 1 existing row, created = f |
Session B with DO SELECT waited 2.1 seconds for A to finish, then received the row A had created. If A ends with ROLLBACK instead of a commit, B creates a new row with that name and gets created = t. Either way, B gets exactly one row. No retry code needed.
How different is it from the DO UPDATE workaround? I measured WAL#
Looking only at results, the DO UPDATE workaround wasn’t wrong either. The difference is in the cost. I measured how big it is while writing this post. The numbers below aren’t taken from the official documentation or other sources. They’re my own measurements.
What I measured is WAL volume. WAL (Write-Ahead Log) is the record of changes that PostgreSQL writes down before it modifies data. Crash recovery and replication run on this record, so when more WAL piles up, disk writes increase and so does the amount to send to replicas.
The measurement conditions were these.
- Environment: the official PostgreSQL 19.0 Docker image (
postgres:19), an Apple Silicon Mac, default server settings - Table: the same structure as the
tagsabove, with 1,000 tags. I turned autovacuum off so it wouldn’t interfere during measurement - Requests: get-or-create on existing tags picked at random. Every request conflicts
- Load: pgbench, the benchmark tool that ships with PostgreSQL, with 4 clients running 50,000 requests each, 200,000 in total
- WAL volume: the difference between
pg_current_wal_insert_lsn()right before and right after the run - Runs: twice per approach, with the table recreated each time
The pgbench script and command I used to measure DO SELECT are below. For the other approaches, I only swapped the INSERT statement.
\set n random(1, 1000)
INSERT INTO bench_tags (name) VALUES ('tag' || :n) ON CONFLICT (name) DO SELECT RETURNING id;pgbench -n -M prepared -c 4 -j 4 -t 50000 -f do_select.sql
WAL left behind by 200,000 conflicting requests (PostgreSQL 19.0, my own pgbench measurements)
The two runs came out nearly identical. The DO UPDATE workaround was 36,573,176 bytes and 36,618,280 bytes (about 35 MB), and DO SELECT was 875,352 bytes (855 kB) both times. That’s about one-fortieth. In throughput, the workaround did about 20,000 per second and DO SELECT a little over 70,000, roughly a 3.5x difference.
The 855 kB for DO SELECT isn’t a record of writing the row, either. ON CONFLICT uses up one number from the id sequence even when there’s a conflict, and the 855 kB is the record of that. It’s also why the ids skipped from 1 to 6 to 8 in the output earlier. When I ran the same experiment on a table that uses the name as its primary key, with no id, the WAL was 0 bytes.
I measured these in Docker on my own Apple Silicon Mac, so the absolute values will differ from environment to environment. Every request conflicted in this setup, so in a real service where new tags are mixed in, the gap will be smaller. Please read it as a ratio between approaches. The CTE approach was similar to
DO SELECTin both WAL and throughput. The difference between those two isn’t speed, it’s the concurrent-request result we saw earlier.
The purple bar in the chart is the one to watch. After DO SELECT, you can attach a locking clause such as FOR UPDATE to hold the returned row so another transaction can’t modify it in the meantime. But lock information is also recorded in the row, so even the weakest lock, FOR KEY SHARE, pushed WAL up to 19 MB and dropped throughput to workaround levels. If you only read the returned row, leave the locking clause off.
Permissions DO SELECT needs: INSERT and SELECT#
DO SELECT reads the row and returns it, so it needs the SELECT privilege in addition to INSERT. I created a role to check, and it ran with just those two. The DO UPDATE workaround is literally an UPDATE, so even a role that only looks up and creates tags needed modification privileges. It got easier to grant only what’s needed.
If the table uses RLS (Row Level Security, a feature where the database filters which rows each user can see), check one more thing. If there’s an INSERT policy but no SELECT policy, you get a new row violates row-level security policy error even when inserting a new row with no conflict, because the row you’re inserting is also checked against the SELECT policy. Adding a locking clause also requires the UPDATE privilege and an UPDATE policy. Which policies apply to which statement is laid out in the CREATE POLICY table in the official docs.
One-page summary#
INSERT ... ON CONFLICT (column) DO SELECT RETURNING ...is available from PostgreSQL 19 and returns the conflicting existing row without modifying it.RETURNINGand the conflict target are required.- Tell a new row from an existing one with
RETURNING (old.id IS NULL) AS created. - Under concurrent requests,
SELECTthenINSERTraised aduplicate keyerror and the CTE approach returned an empty result, whileDO SELECTwaited and returned the existing row. - With 200,000 conflicts, the
DO UPDATEworkaround left 35 MB of WAL andDO SELECTleft 855 kB. Adding a locking clause brings it back up to 19 MB. INSERTandSELECTprivileges are enough. If you use RLS, you need aSELECTpolicy.
Next time you reach for SELECT and then INSERT#
Get-or-create is a small feature, a few lines of code, but the gap between those few lines produces errors that only show up now and then in production. With PostgreSQL 19, you can leave that gap to the database.
If you can upgrade, search your code for lines like DO UPDATE SET name = EXCLUDED.name. If the UPDATE is there not to change a value but to get the row back, it’s a candidate to swap for DO SELECT. An upsert that really needs to change values is still a job for DO UPDATE, as it is now.
If you can’t upgrade yet, check which workaround you’re on. The DO UPDATE workaround pays a write cost, but you always get a result back. The CTE approach is light, but under concurrent requests you can get an empty result. If you’re on the CTE alone with no retry, that one is more urgent.

Leave a comment
Couldn't load the comments. Check your connection and try again.