PostgreSQL ON CONFLICT: Why DO NOTHING RETURNING Can Be Empty

Two workers receive the same request key. Both try to create its database record, and both need the stored payload afterward. You add ON CONFLICT DO NOTHING RETURNING request_key, payload, expecting either the new record or the one that already exists. One worker gets no row back. Did the record disappear, or did deduplication fail?

Neither conclusion follows. PostgreSQL’s RETURNING reports only the rows that the command inserts or updates; it does not look up an existing conflicting row. Under concurrency, a competing insert can block on an uncommitted transaction before ultimately doing nothing. Command completion, row existence, and returned output are three distinct outcomes.

This guide examines that distinction using PostgreSQL's release-pinned isolation tests, outlines a two-session reproduction, and defines a bounded get-or-create control flow. The SQL blocks below are source-backed examples rather than transcripts of live executions.

On this page
  1. Evidence and method: compare the two REL_17_0 permutations
  2. Separate uniqueness arbitration from snapshot visibility
  3. Reproduction: prepare a disposable two-session database
  4. Read the expected outcomes without inventing a test run
  5. Build a get-or-create path that admits an empty result
  6. Failure modes and trade-offs: do not update just to get a row
  7. Limitations of the release-pinned analysis
  8. Action checklist: test both endings before trusting get-or-create

Evidence and method: compare the two REL_17_0 permutations#

Evidence inspected: 2026-11-25T17:57:15.112Z. The evidence anchor is PostgreSQL’s REL_17_0 release tag, not a moving development branch. The official isolation-test specification supplies the SQL and execution ordering; its paired expected-output file supplies the project’s recorded expectations. Reading an expected-output file is not the same as running that test locally.

The useful comparison changes one event: whether the first transaction commits or aborts. The competing inserts otherwise target the same primary-key value. These are the directly checkable artifact observations:

  • The REL_17_0 test specification opens both sessions at READ COMMITTED.
  • The specification schedules the second insert before either COMMIT or ABORT ends the first transaction.
  • The expected-output file marks the second insert as waiting in both permutations.
  • After the first transaction commits, the expected SELECT returns donothing1; after it aborts, the expected SELECT returns donothing2.
  • The pinned test contains a separate SELECT but no RETURNING clause.

That last boundary matters. The test directly supports the wait-and-resolve sequence and the later lookup. The prediction about RETURNING comes from combining those artifacts with the official INSERT contract: the engine returns only rows that were actually inserted or updated. The reproduction includes that clause explicitly so you can verify the deduced behavior without confusing it with upstream test output.

Separate uniqueness arbitration from snapshot visibility#

Suppose transaction A inserts a key and stays open. Transaction B cannot safely treat the key as free because A might commit, nor can it assume a conflict because A might abort. The index uniqueness-check documentation describes waiting for the competing transaction and then checking again.

Uniqueness arbitration decides only whether B can proceed with its insert; it never converts a skipped insert into returned output. When A commits, B follows the DO NOTHING path and produces zero inserted rows to return. When A rolls back, B inserts and returns its own row. Either way, key uniqueness holds.

A read snapshot answers a different question: which row versions may this command read? The transaction isolation documentation says a normal SELECT at READ COMMITTED sees data committed before that query began. It also explicitly allows DO NOTHING to suppress an insertion because of a transaction whose effects are not visible to the insert’s snapshot.

Blocking on a lock does not grant the current statement a new read snapshot once it wakes up. At this isolation level, snapshot refreshes occur only when the next command begins. That makes the test's separate select2 step crucial: resolving a uniqueness conflict and reading the winning row require distinct commands.

Reproduction: prepare a disposable two-session database#

Open two interactive SQL clients connected to a disposable database on a patched, supported PostgreSQL server, and note the server version. The pinned release tag serves strictly as an analytical baseline, not advice to run an unpatched minor version. Always test with synthetic fixtures rather than production tables.

Follow this sequence; the code blocks below expand its first four steps:

  1. Open two sessions to the same disposable database and create conflict_demo once with autocommit enabled.
  2. In session A, begin READ COMMITTED, insert example-a, and leave the transaction open.
  3. In session B, begin READ COMMITTED and run the competing INSERT with DO NOTHING and RETURNING before ending session A.
  4. Commit session A, then run a separate SELECT in session B and commit session B.
  5. Repeat with example-b in both sessions, replacing session A’s COMMIT with ROLLBACK.

Execute the schema setup once with autocommit active so the table commits before the second session queries it. Avoid temporary tables, since both sessions must share the same relation.

SELECT version();
CREATE TABLE conflict_demo (
    request_key text PRIMARY KEY,
    payload text NOT NULL
);

Session A establishes the competing, uncommitted record. Stop after this block; do not commit yet.

BEGIN ISOLATION LEVEL READ COMMITTED;
INSERT INTO conflict_demo (request_key, payload)
VALUES ('example-a', 'from-a')
ON CONFLICT (request_key) DO NOTHING
RETURNING request_key, payload;

Next, submit the competing statement in session B. Because session A remains uncommitted, the documented behavior requires B to block on the active transaction instead of returning the stored payload right away.

BEGIN ISOLATION LEVEL READ COMMITTED;
INSERT INTO conflict_demo (request_key, payload)
VALUES ('example-a', 'from-b')
ON CONFLICT (request_key) DO NOTHING
RETURNING request_key, payload;

While B is waiting, return to session A and end its transaction:

COMMIT;

After B’s insert finishes, issue this as a new command in session B, then end B’s transaction:

SELECT request_key, payload
FROM conflict_demo
WHERE request_key = 'example-a';
COMMIT;

If a lock or statement timeout aborts the wait, roll back the failed transaction and close the competing transaction before retesting with a unused key. Timeouts raise errors rather than producing the empty successful result studied here. Never leave open transactions lingering.

Read the expected outcomes without inventing a test run#

The following table is a deduction from the pinned test and documented RETURNING semantics. It is not measured output from this article’s authoring environment.

Session A ends with B’s competing insert B’s RETURNING result B’s later SELECT
COMMIT Skips the conflicting row No rows The row with payload from-a
ROLLBACK, using a fresh key Inserts its own row The row with payload from-b The row with payload from-b

For the rollback branch, repeat the insert blocks with example-b in both sessions and change the later lookup to that key. Roll back A while B waits. Fresh keys avoid confusing a previous committed row with the transaction you intended to test.

Also distinguish this race from an ordinary duplicate against a long-committed row. That duplicate produces no RETURNING row too, even without the competing transaction wait. Empty output alone therefore cannot diagnose contention, prove absence, or tell you which transaction originally created the record.

Build a get-or-create path that admits an empty result#

For a create-only operation, treat RETURNING strictly as proof of insertion. Receiving a row confirms this statement wrote it; receiving zero rows means you must run a follow-up query to fetch the existing record. In the commit scenario above, that follow-up query begins after A commits, making A's row visible.

A useful application flow has explicit outcomes rather than a single boolean named success:

  1. Inserted: accept the returned record provisionally, finish any related database work, and commit before reporting durable success.
  2. Conflict found: when the insert returns nothing, execute a new lookup for the same key. Return or inspect the stored record according to the application’s duplicate-request contract.
  3. Still absent: if that lookup also returns nothing, do not manufacture a record. Stop or retry the database decision under a finite attempt budget.
  4. Database error: handle the actual error separately; an exception is not equivalent to a successful insert that returned zero rows.

Including the absent branch is intentional. A concurrent delete could remove the winning row before your follow-up query starts, or a stricter isolation level could hide it. Workloads that allow deletions or demand row stability across multi-step operations need explicit locking or lifecycle rules beyond this two-statement pattern.

Nor should the duplicate path blindly replace stored data with the new request’s payload. In this example, from-a and from-b are intentionally different. Deciding whether that difference means an accepted replay or a rejected key reuse is application policy, not something uniqueness decides for you.

This extends the client-side boundary in Python Requests timeouts and retries: an HTTP retry policy determines when another request may be sent; this database path determines what a competing create can actually return. Neither layer alone proves an external side effect happened exactly once.

Failure modes and trade-offs: do not update just to get a row#

A no-change update still selects the update branch. Replacing DO NOTHING with DO UPDATE can make a conflicting record available through RETURNING, yet doing so alters the statement's semantics. According to the INSERT documentation, that path demands UPDATE privileges and locks conflicting tuples. Check how triggers, row locks, and write amplification behave on your table before assigning dummy updates just to force a return value.

A conditional update can still return nothing. The same reference states that a row locked but not updated because the update’s WHERE condition is false is not returned. Switching syntax is not a universal promise that every input produces an output record.

Specify the intended conflict target. The example uses ON CONFLICT (request_key). Omitting the target with DO NOTHING suppresses conflicts across every applicable unique index and constraint. On tables with multiple unique rules, omitting the target obscures why zero rows came back: another constraint may have tripped instead of the request key you intended to deduplicate.

Choose the retry scope from isolation, not habit. A new command gets a new snapshot at READ COMMITTED. By contrast, Repeatable Read pins its snapshot to the first statement in the transaction, and the documentation instructs callers to retry the entire transaction upon serialization failure. Never embed the fallback SELECT inside a longer Repeatable Read or Serializable transaction expecting Read Committed visibility.

Keep database retries separate from outside effects. This walkthrough performs no network call or other external action inside the retry path. Adding one requires its own idempotency and reconciliation rules. A unique database key cannot establish whether an unrelated service already acted.

Limitations of the release-pinned analysis#

  • This is an inspection of PostgreSQL REL_17_0 artifacts, not a local database execution or a benchmark.
  • The published regression test does not exercise RETURNING; the RETURNING predictions below are deductions from the documented command semantics.
  • The reproduction assumes READ COMMITTED, a plain table, and no triggers, row-level security, or concurrent deletion.
  • The analysis does not verify every later PostgreSQL patch or the behavior of another database engine.

The expected-output artifact supports no latency or throughput claims. Its waiting annotations confirm event ordering, not lock duration or system capacity. When documenting your own test runs, record the exact server version, table definition, statement sequence, and returned rows together.

Share only synthetic fixtures and sanitized results. The separate note on SQL-debugging privacy concerns how copied database text is handled; it is not evidence for the transaction behavior analyzed here.

Action checklist: test both endings before trusting get-or-create#

Inspect the raw SQL your application emits rather than trusting an ORM helper's name. Determine whether your code expects creation, retrieval, or mutation, and verify which of those behaviors the query actually guarantees.

  • Confirm the isolation level and the unique constraint that represents your request identity.
  • Keep inserted, conflicting, absent-after-lookup, and error outcomes distinguishable.
  • Exercise both commit and rollback of the competing creator, using a new synthetic key for each case.
  • Verify that any fallback lookup is a new command, and document the assumptions about deletion and access policies.
  • Bound retries, finish transactions promptly, and keep external effects outside this unproven guarantee.

Include both concurrent commit and concurrent rollback permutations in your integration suite, and assert that the test fails if application logic mistakes an empty RETURNING set for a missing record.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *