ON CONFLICT DO SELECT (take 3)

From: Viktor Holmberg <v(at)viktorh(dot)net>
To: pgsql-hackers(at)postgresql(dot)org
Subject: ON CONFLICT DO SELECT (take 3)
Date: 2025-10-07 11:56:46
Message-ID: d631b406-13b7-433e-8c0b-c6040c4b4663@Spark
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Hi!

This patch implements ON CONFLICT DO SELECT.
This feature would be very handy in bunch of cases, for example idempotent APIs.
I’ve worked around the lack of this by using three statements, like: SELECT -> INSERT if not found -> SELECT again for concurrency safety. (And having to do that dance is driving me nuts)

Apart from the convenience, it’ll also have a performance boost in cases with high latency.

As evidence of that fact that this is needed, and workarounds are complicated, see this stack overflow question: https://stackoverflow.com/questions/16123944/write-a-postgres-get-or-create-sql-query or this entire podcast episode (!) https://www.youtube.com/watch?v=59CainMBjtQ

This patch is 85% the work of Andreas Karlsson and the reviewers (Dean Rasheed, Joel Jacobson, Kirill Reshke) in this thread: https://www.postgresql.org/message-id/flat/2b5db2e6-8ece-44d0-9890-f256fdca9f7e%40proxel.se, which unfortunately seems to have stalled.
I’ve fixed up all the issues mentioned in that thread (at least I think so), plus some minor extra stuff:

1. Made it work with partitioned tables
2. Added isolation test
3. Added tests for row-level security
4. Added tests for partitioning
5. Docs updated
6. Comment misspellings fixed
7. Renamed struct OnConflictSetState -> OnConflictActionState

I’ve kept the patches proposed there separate, in case any of the people involved back then would like to pick it up again.

Grateful in advance to anyone who can help reviewing!

/Viktor

Attachment Content-Type Size
0001-Add-support-for-ON-CONFLICT-DO-SELECT-FOR.patch application/octet-stream 51.4 KB
0002-Review-comments-for-ON-CONFLICT-DO-SELECT.patch application/octet-stream 35.1 KB
0003-Remaning-fixes-for-ON-CONFLICT-DO-SELECT.patch application/octet-stream 41.3 KB

Browse pgsql-hackers by date

  From Date Subject
Next Message Viktor Holmberg 2025-10-07 12:01:20 Re: INSERT ... ON CONFLICT DO SELECT [FOR ...] take 2
Previous Message Hayato Kuroda (Fujitsu) 2025-10-07 11:53:34 RE: Newly created replication slot may be invalidated by checkpoint