Re: Why the ERROR: duplicate key violates uniqueconstraint "master_pkey" is raised? - Is this a Bug?

From: "Phoenix Kiula" <phoenix(dot)kiula(at)gmail(dot)com>
To: "Anoo Sivadasan Pillai" <aspillai(at)in(dot)rm(dot)com>
Cc: "Reece Hart" <reece(at)harts(dot)net>, pgsql-general(at)postgresql(dot)org
Subject: Re: Why the ERROR: duplicate key violates uniqueconstraint "master_pkey" is raised? - Is this a Bug?
Date: 2007-09-25 04:56:12
Message-ID: e373d31e0709242156l164b4e90t6c62c371b4a234b0@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On 25/09/2007, Anoo Sivadasan Pillai <aspillai(at)in(dot)rm(dot)com> wrote:
>
>
>
>
> Hi,
>
> On further testing I found the same behaviour in Unique keys too, The following batch can reproduce the behaviour.
>
> CREATE TABLE master ( m1 INT primary key , m2 int unique ) ;
>
> INSERT INTO master VALUES ( 1, 1 ) ;
>
> INSERT INTO master VALUES ( 2, 2) ;
>
> UPDATE master SET m2 = m2 + 1;
>
>

Isn't this expected behavior? When you update the m2 of the first
record, it becomes 2 and violates the unqiue constraint as the second
row already has an m2 value of 2.

I have missed the thread, but this reeks of an unusual DB design. If
your really want the updates to go in reverse order so that keys are
not violated, you can do that in your application -- SELECT the keys
you wish to update sorted in DESC order by m2, and then foreach of
them, just increment the value accordingly. If you wrap this in a
transaction, it'll be pretty fast, depending on how many rows you're
talking about (I've found great speeds on records up to 50,000 for a
live DB).

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Reece Hart 2007-09-25 05:02:45 Re: Why the ERROR: duplicate key violates uniqueconstraint "master_pkey" is raised? - Is this a Bug?
Previous Message Pavel Stehule 2007-09-25 04:46:35 Re: set returning functions.