ON CONFLICT DO SELECT (take 3)
Viktor Holmberg <v@viktorh.net>
From: Viktor Holmberg <v@viktorh.net>
To: pgsql-hackers@postgresql.org
Date: 2025-10-07T11:56:46Z
Lists: pgsql-hackers
Commits
Same data as JSON:
GET /api/v1/messages/:b64id/commits
the thread's linked commits as JSON, with link sources.
API reference →
-
Add support for INSERT ... ON CONFLICT DO SELECT.
- 88327092ff06 19 (unreleased) landed
-
doc: Fix statement about ON CONFLICT and deferrable constraints.
- f188bc5145b5 15.16 landed
- 4c4fa53b9d2d 14.21 landed
- 8348004b54a7 16.12 landed
- 7a02ac28ab11 17.8 landed
- e9443a55265f 19 (unreleased) landed
- ae627d8a3cb0 18.2 landed
-
Fix ON CONFLICT ON CONSTRAINT during REINDEX CONCURRENTLY
- 2bc7e886fc1b 19 (unreleased) cited
Attachments
- 0001-Add-support-for-ON-CONFLICT-DO-SELECT-FOR.patch (application/octet-stream) patch 0001
- 0002-Review-comments-for-ON-CONFLICT-DO-SELECT.patch (application/octet-stream) patch 0002
- 0003-Remaning-fixes-for-ON-CONFLICT-DO-SELECT.patch (application/octet-stream) patch 0003
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