Re: BUG #18279: Duplicate key violation and Deadlock when using ON CONFLICT/DO UPDATE with multiple unique indexes - Mailing list pgsql-bugs

From Peter Geoghegan
Subject Re: BUG #18279: Duplicate key violation and Deadlock when using ON CONFLICT/DO UPDATE with multiple unique indexes
Date
Msg-id CAH2-Wz=fxhEjM-gdS2TO+Vn0=4p0DLREg1cdSO5+96MNT1Yv8A@mail.gmail.com
Whole thread Raw
In response to BUG #18279: Duplicate key violation and Deadlock when using ON CONFLICT/DO UPDATE with multiple unique indexes  (PG Bug reporting form <noreply@postgresql.org>)
Responses Re: BUG #18279: Duplicate key violation and Deadlock when using ON CONFLICT/DO UPDATE with multiple unique indexes  (노영은 <nye7181@gmail.com>)
List pgsql-bugs
On Wed, Jan 10, 2024 at 4:28 AM PG Bug reporting form
<noreply@postgresql.org> wrote:
> I have a table with a primary key and a unique index.
> First, I ran an INSERT query and then several INSERT INTO ON CONFLICT DO
> UPDATE queries in parallel.
> This will almost always result in Duplicate key violations, and sometimes
> Deadlocks.
> When I removed the unique index, there was no Duplicate key violation or
> Deadlock.

This is not a bug. The statements you've shown use "ON CONFLICT (id)
DO UPDATE", which will make the primary key the arbiter index -- the
index used for upserting. The duplicate violation errors relate to the
unique index, though.

In general the implementation only uses one arbiter index to decide
whether to insert or to update each row (barring certain edge cases
where the table has multiple equivalent/redundant unique indexes).
It's possible that you'll get the behavior you expect by specifying
"ON CONFLICT (user_id, date) DO UPDATE" instead -- though I can't be
sure of that.

--
Peter Geoghegan



pgsql-bugs by date:

Previous
From: "David G. Johnston"
Date:
Subject: Re: BUG #18281: Superuser can rename the schema with the prefix "pg_" (Applies to all versions of postgresql)
Next
From: Tom Lane
Date:
Subject: Re: BUG #18281: Superuser can rename the schema with the prefix "pg_" (Applies to all versions of postgresql)