Re: duplicate key violate error - Mailing list pgsql-general

From Merlin Moncure
Subject Re: duplicate key violate error
Date
Msg-id BANLkTikJAAC0jDW_+y9VOdVpH9NXckjNxA@mail.gmail.com
Whole thread Raw
In response to duplicate key violate error  (AI Rumman <rummandba@gmail.com>)
List pgsql-general
On Tue, Jun 14, 2011 at 3:30 AM, AI Rumman <rummandba@gmail.com> wrote:
> Hi,
>
> I got duplicate key violate error in the db log for the following query:
> INSERT INTO tab1 ( SELECT '1611576', '1187865' WHERE NOT EXISTS (
> SELECT 1 FROM tab1         WHERE id='1611576' AND id2='1187865'    )    )
>
> The error occured during production time.
> But when I manually executed the query, it inserted one row with success and
> next time it inserted 0 rows.

Unfortunately the operation above is not atomic.  This is a classic
concurrency problem that everyone has to deal with -- there is no way
at present to rely on a simple row level lock to prevent concurrent
inserts to the same key.  You have a few of ways to deal with this:

*) retry the statement (personally not a big fan of this method)
*) lock the table (lousy concurrency)
*) advisory lock might work, if you must have concurrency and your key
is an integer. be careful, and do not overuse the technique.

merlin

pgsql-general by date:

Previous
From: Erwin Moller
Date:
Subject: psql reports back wrong number of affected rows.
Next
From: Merlin Moncure
Date:
Subject: Re: thoughts on interactive query