Re: Duplicate Unique Key constraint error

From: Michael Glaesemann <grzm(at)seespotcode(dot)net>
To: "Harpreet Dhaliwal" <harpreet(dot)dhaliwal01(at)gmail(dot)com>
Cc: "Ron St-Pierre" <ron(dot)pgsql(at)shaw(dot)ca>, "Postgres General" <pgsql-general(at)postgresql(dot)org>
Subject: Re: Duplicate Unique Key constraint error
Date: 2007-07-10 18:35:16
Message-ID: 070863BA-FF3C-4894-9C51-18CD3BDFEBA4@seespotcode.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general pgsql-odbc


On Jul 10, 2007, at 13:22 , Harpreet Dhaliwal wrote:

> Transaction 1 started, saw max(dig_id) = 30 and inserted new
> dig_id=31.
> Now the time when Transaction 2 started and read max(dig_id) it was
> still 30
> and by the time it tried to insert 31, 31 was already inserted by
> Transaction 1 and hence the unique key constraint error.
>
> I thought this would be taken care by the database itself by
> locking the
> transactions but now I really don't know how does this locking
> takes place
> in postgres.

Why would the server lock the table? It can't know your intention is
to add one to the number returned and insert. If this is what you
want, you have to lock the table explicitly.

> Please guide me throug to get rid of this problem.

This exact reason is why sequences are often used for primary keys. I
recommend you change your primary key.

Michael Glaesemann
grzm seespotcode net

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Richard Huxton 2007-07-10 18:51:58 Re: Adjacency Lists vs Nested Sets
Previous Message Harpreet Dhaliwal 2007-07-10 18:22:47 Re: Duplicate Unique Key constraint error

Browse pgsql-odbc by date

  From Date Subject
Next Message Tom Lane 2007-07-10 19:09:14 Re: Duplicate Unique Key constraint error
Previous Message Harpreet Dhaliwal 2007-07-10 18:22:47 Re: Duplicate Unique Key constraint error