From: | Lincoln Yeoh <lyeoh(at)pop(dot)jaring(dot)my> |
---|---|
To: | "Peter Darley" <pdarley(at)kinesis-cem(dot)com>, "Mark Harrison" <mh(at)pixar(dot)com>, <pgsql-general(at)postgresql(dot)org> |
Subject: | Re: most idiomatic way to "update or insert"? |
Date: | 2004-08-05 01:49:16 |
Message-ID: | 6.1.2.0.1.20040805094112.01bb6ec0@localhost |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-general |
I don't think that works - there's a race condition if you do not do any
locking.
Why:
Before a transaction that inserts rows is committed, other transactions are
not aware of the inserted rows, so the select returns no rows.
So:
You can either create a unique index and catch insert duplicate failures.
Or:
lock the relevant tables, then do the select ... update/insert or insert
... select , or whatever it is you want to do.
Or:
both.
Test it out yourself.
At 07:51 AM 8/5/2004, Peter Darley wrote:
>Mark,
> It's not canonical by any means, but what I do is:
>
>update foo set thing='stuff' where name = 'xx' and thing<>'stuff';
>insert into foo (name, thing) (select 'xx' as name, 'stuff' as thing where
>not exists (select 1 from foo where name='xx'));
>
> I believe if you put these on the same line it will be a single
>transaction. It has the benefit of not updating the row if there aren't
>real changes. It's plenty quick too, if name is indexed.
>
>Thanks,
>Peter Darley
From | Date | Subject | |
---|---|---|---|
Next Message | Gunasekaran Balakrishnan | 2004-08-05 03:53:25 | Re: Test case for bug fix in 7.4.3 |
Previous Message | Greg Stark | 2004-08-05 01:46:39 | Re: most idiomatic way to "update or insert"? |