Thanks for the clarification guys! That was not the behavior I was expecting (as you can tell), so I learned something new today. :)
In my case I don't want an update (there are only the 2 fields, so it's just insert or delete), so I'll fire the insert as it is (that'll get the cases where it's not a concurrent update failure) and catch the failure to verify that the data exists - if it does, I'll ignore the failure; if not, i'll throw an exception.
On Sat, Jun 27, 2015 at 9:47 PM, Pavel Stehule <pavel.stehule@gmail.com> wrote: > you can protect it against this issue with locking - in this case you can > try "for update" clause > > http://www.postgresql.org/docs/9.4/static/explicit-locking.html > > insert into Favorite (patronId, titleId) > select 123, 234 > where not exists ( > select 1 from Favorite where patronId = 123 and titleId = 234 for update > )
That won't work reliably either -- a SELECT ... FOR UPDATE will still use an MVCC snapshot. The looping + subxact pattern must be used [1] if a duplicate violation isn't acceptable. ON CONFLICT DO UPDATE should be preferred once 9.5 is released.