Scrivio Interview library
DebuggingIntermediate7 min read · updated 12 November 2026

A Spring service upserts with INSERT ... ON CONFLICT DO NOTHING and then SELECTs the row to get its id. Under load some requests get no row back from the SELECT, and the sequence has big gaps. Explain both effects and a better pattern.

The sequence gaps are normal: the id is taken from the sequence when the row is built, before the conflict is detected, and sequence values are never given back, so every conflicting upsert burns one. The missing rows come from the follow-up SELECT not seeing the row the conflict was about, for example because it runs with an older REPEATABLE READ snapshot, on a replica or another connection; and DO NOTHING ... RETURNING returns nothing on conflict, so the caller must handle that case. The better pattern is ON CONFLICT (key) DO UPDATE SET key = EXCLUDED.key RETURNING id, which always returns the id at the cost of a row version write, or a retry loop around the SELECT, run as a native query because JPA's save() is not an atomic upsert.

Why this question is asked

Get-or-create is everywhere: find the tag with this name or create it, find the customer with this external id or create one, and in both cases return the id. The two-step version, insert if missing and then select, looks safe because the insert has ON CONFLICT DO NOTHING. Under load it surprises teams twice: some requests find no row at all, and the ids jump by thousands. Interviewers ask this because both effects come from details of how PostgreSQL implements upserts, sequences and snapshots. In this answer, we will explain the sequence gaps, then the missing rows, look at what RETURNING does on conflict, and build a pattern that always returns the id.

1The Pattern in Question

The service keeps a tags table with a unique name, and for each incoming tag it runs two statements.

SQL
CREATE TABLE tags (id bigserial PRIMARY KEY, name text NOT NULL UNIQUE);
-- Step 1: create if missing
INSERT INTO tags (name) VALUES ('java') ON CONFLICT (name) DO NOTHING;
-- Step 2: read the id
SELECT id FROM tags WHERE name = 'java';

Most of the time this works. Let us look at the two strange effects separately, because they have different causes.

2Why the Sequence Has Big Gaps

The id column gets its value from a sequence through a default expression. PostgreSQL evaluates the defaults when it builds the new row, and only then tries to insert it and discovers the conflict on the unique index. By that time nextval() has already been called. Sequences are deliberately non-transactional: a value handed out is never returned, even if the statement does nothing or the transaction rolls back, because giving values back would force every session to wait for every other.

SQL
INSERT INTO tags (name) VALUES ('java') ON CONFLICT (name) DO NOTHING; -- id 1 inserted
INSERT INTO tags (name) VALUES ('java') ON CONFLICT (name) DO NOTHING; -- conflict: value 2 burned
INSERT INTO tags (name) VALUES ('java') ON CONFLICT (name) DO NOTHING; -- conflict: value 3 burned
INSERT INTO tags (name) VALUES ('kotlin') ON CONFLICT (name) DO NOTHING; -- id 4
SELECT id, name FROM tags;
-- 1 | java
-- 4 | kotlin

If 99 percent of calls hit an existing tag, the sequence advances 100 times faster than the table grows. That is harmless, with one caveat: on very busy tables an int column can run out years earlier than expected, so the id should be bigint. What we must never do is rely on ids being gapless, for example to count rows or to number invoices; legal invoice numbers need a separate, transactional counter.

3Why the SELECT Sometimes Finds Nothing

The INSERT says do nothing because the row exists. The SELECT then has to see that row, and whether it does depends on its snapshot, the set of committed transactions it is allowed to see. Under READ COMMITTED, each statement takes a fresh snapshot, and if the INSERT found another transaction's uncommitted row for the same name, it waited for that transaction to finish, so in the simple case the SELECT does see the committed row. The empty results come from the cases where the SELECT's view is older or somewhere else.

Under REPEATABLE READ, the whole transaction uses the snapshot taken at its first statement. If the other transaction committed the tag after that moment, the row is invisible to our SELECT. In PostgreSQL, the INSERT itself may already fail at this isolation level with could not serialize access due to concurrent update, because it conflicts with a row its snapshot cannot see. Another frequent cause is infrastructure: the SELECT is routed to a read replica that has not replayed the insert yet, for example by a routing data source that sends read-only transactions to replicas, or it runs on a different connection outside the transaction. A concurrent delete of the tag between the two statements gives the same symptom.

Step throughMissing row under REPEATABLE READ
Request APostgreSQLRequest B
BEGIN REPEATABLE READ; first query takes snapshot
INSERT 'java' and COMMIT
INSERT 'java' ON CONFLICT DO NOTHING
conflict with a row the snapshot cannot see (may raise 40001)
SELECT id WHERE name = 'java'
0 rows: row committed after B's snapshot

6 messages in order. Play them, or step through them one at a time.

4What RETURNING Does on Conflict

A natural idea is to drop the second statement and use RETURNING id on the insert. That returns the id when the row is inserted, but DO NOTHING means exactly that: on conflict no row is produced, so RETURNING returns nothing.

SQL
INSERT INTO tags (name) VALUES ('java') ON CONFLICT (name) DO NOTHING RETURNING id;
-- (0 rows) the tag already existed; no id comes back

So any caller that uses DO NOTHING ... RETURNING must treat an empty result as a normal outcome and look the row up some other way, which brings back the second statement and its visibility questions.

5A Pattern That Always Returns the Id

The most robust option is to turn the conflict into an update that changes nothing meaningful. DO UPDATE locks the existing row and makes it part of the statement's result, even if it was committed by a transaction our snapshot cannot see in READ COMMITTED, so RETURNING always yields exactly one id.

SQL
INSERT INTO tags (name) VALUES ('java')
ON CONFLICT (name) DO UPDATE SET name = EXCLUDED.name
RETURNING id;
-- 1 always one row: inserted or existing
Step throughGet-or-create that always returns an id
  1. SELECT id WHERE name = ?on the primary, same transaction
  2. Found a row?
    YesReturn the idNoUpsert
  3. INSERT ... ON CONFLICT DO UPDATE SET name = EXCLUDED.name RETURNING idalways one row
  4. Return the id

4 steps in order. Play them, or step through them one at a time.

The cost is that every call on an existing tag writes a new row version, which produces WAL, dead tuples for vacuum and, if there is an update trigger or CDC, extra events. For a table with heavy repeat traffic, a cheaper variant is to try a plain SELECT first and only run the upsert when it finds nothing: most calls then do a cheap read, and the rare creation path is still race-free. The other option is the original two statements in a loop that retries until the SELECT finds the row or the INSERT creates it, which avoids the extra write but needs care and a retry limit.

6Doing It From Spring and JPA

Spring Data's save() is not an upsert. For an entity whose id is generated, save() calls persist() and the insert fails on the unique name with a constraint violation when another request created the tag first. For an entity with an assigned id, save() calls merge(), which first selects by id and then inserts or updates, and the same race exists between those two steps. So we use a native query.

Java
@Query(value = """
INSERT INTO tags (name) VALUES (:name)
ON CONFLICT (name) DO UPDATE SET name = EXCLUDED.name
RETURNING id
""", nativeQuery = true)
Long upsertAndGetId(String name); // returns the id; see the note below about @Modifying

Whether a native INSERT with RETURNING works best as a plain @Query or needs @Modifying depends on the Spring Data and Hibernate versions, so check your version; JdbcTemplate.queryForObject is a dependable alternative. It also matters that this query runs on the primary, never on a read-only replica route.

7Follow-up questions

Does ON CONFLICT DO UPDATE also burn sequence values?

Yes. The default is evaluated before the conflict is detected in both cases, so every upsert that hits an existing row consumes one value whether the action is DO NOTHING or DO UPDATE. Only a SELECT-first approach avoids burning values on the common path.

Would SERIALIZABLE isolation fix the missing rows?

It would turn the silent empty result into an explicit serialization failure, SQLSTATE 40001, which the application must catch and retry. That is safer than returning nothing, but for a simple get-or-create the DO UPDATE ... RETURNING pattern at READ COMMITTED is simpler and does not need retries.

8Conclusion

In this answer, we saw that sequence gaps come from nextval() being evaluated before the conflict is found and values never being returned, so ids should be bigint and never assumed gapless. The empty SELECT comes from a view of the data that cannot see the conflicting row, such as an older REPEATABLE READ snapshot, a replica or another connection, and DO NOTHING ... RETURNING returns nothing on conflict. ON CONFLICT DO UPDATE SET key = EXCLUDED.key RETURNING id always returns the id at the cost of a row version, and in Spring it runs as a native query.

What to say in the interviewAbout 90 seconds aloud

Open with

There are two separate effects. The gaps are expected: the id default calls nextval when the row is built, before PostgreSQL discovers the conflict on the unique index, and sequence values are never handed back, so every upsert that hits an existing row burns a number.

Then, if they want more

That's fine as long as the column is bigint and nobody relies on gapless ids. The empty SELECT is a visibility problem. The INSERT did nothing because some transaction's row exists, but the SELECT can only see rows committed before its snapshot.

At READ COMMITTED the insert waits for a concurrent inserter, so the simple case works, but under REPEATABLE READ the snapshot can predate the other commit, and PostgreSQL may even raise a serialization error; reads routed to a replica or a different connection, or a concurrent delete, give the same symptom.

Also, DO NOTHING RETURNING returns zero rows on conflict, so callers must handle that. My preferred pattern is INSERT ... ON CONFLICT on the key DO UPDATE SET name = EXCLUDED.name RETURNING id, which always returns exactly one id, accepting a new row version on each hit; for read-heavy cases I'd SELECT first and upsert only on a miss.

In JPA I'd use a native query, because save does persist or merge, not an atomic upsert.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A Spring service upserts with INSERT ... ON CONFLICT DO NOTHING and then SELECTs the row...": https://scrivio-interview-library.netlify.app/databases/sql-fundamentals/b2deadb8ca/