Re: duplicate key violate error

From: "Albe Laurenz" <laurenz(dot)albe(at)wien(dot)gv(dot)at>
To: "AI Rumman *EXTERN*" <rummandba(at)gmail(dot)com>, "pgsql-general General" <pgsql-general(at)postgresql(dot)org>
Subject: Re: duplicate key violate error
Date: 2011-06-14 12:35:04
Message-ID: D960CB61B694CF459DCFB4B0128514C20686FB74@exadv11.host.magwien.gv.at
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

AI Rumman wrote:
> 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.
>
> \d tab1
> id int
> id2 int
> primary key (id,id2)
>
> So, any idea why the error occurred at production time.

Concurrency?

Session 1:

CREATE TABLE tab1 (
id integer NOT NULL,
id2 integer NOT NULL,
PRIMARY KEY (id, id2)
);

START TRANSACTION;

INSERT INTO tab1
(SELECT '1611576', '1187865' WHERE NOT EXISTS
(SELECT 1 FROM tab1 WHERE id='1611576' AND id2='1187865')
);

Session 2:

START TRANSACTION;

INSERT INTO tab1
(SELECT '1611576', '1187865' WHERE NOT EXISTS
(SELECT 1 FROM tab1 WHERE id='1611576' AND id2='1187865')
);

Session 1:

COMMIT;

Session 2:

ERROR: duplicate key value violates unique constraint "tab1_pkey"

Yours,
Laurenz Albe

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Craig Ringer 2011-06-14 12:49:48 Re: Proposition fetch cursors
Previous Message Vick Khera 2011-06-14 12:14:34 Re: PGP encrypt/decrypt - Prereqistes