From: | Merlin Moncure <mmoncure(at)gmail(dot)com> |
---|---|
To: | AI Rumman <rummandba(at)gmail(dot)com> |
Cc: | pgsql-general General <pgsql-general(at)postgresql(dot)org> |
Subject: | Re: duplicate key violate error |
Date: | 2011-06-14 14:55:08 |
Message-ID: | BANLkTikJAAC0jDW_+y9VOdVpH9NXckjNxA@mail.gmail.com |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-general |
On Tue, Jun 14, 2011 at 3:30 AM, AI Rumman <rummandba(at)gmail(dot)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
From | Date | Subject | |
---|---|---|---|
Next Message | Merlin Moncure | 2011-06-14 15:00:54 | Re: thoughts on interactive query |
Previous Message | Erwin Moller | 2011-06-14 14:45:02 | psql reports back wrong number of affected rows. |