Re: INSERT OR UPDATE

From: Andrew - Supernews <andrew+nonews(at)supernews(dot)com>
To: pgsql-general(at)postgresql(dot)org
Subject: Re: INSERT OR UPDATE
Date: 2006-01-03 06:32:04
Message-ID: slrndrk6j4.2iki.andrew+nonews@atlantis.supernews.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On 2006-01-03, Tony Wasson <ajwasson(at)gmail(dot)com> wrote:
> On 1/2/06, Julian Scarfe <julian(at)avbrief(dot)com> wrote:
>> I'm keeping config information for an application in a series of related
>> tables. I'd like a command that INSERTs data if it's new, or UPDATEs it if
>> the key is duplicated.
>
> A MERGE trigger will do exactly what you are asking for.
>
> http://archives.postgresql.org/pgsql-sql/2004-05/msg00135.php
>
> Send all your data as INSERTS.
> The trigger will run a function to see if the row exists.
> If the row exists -> rewrite it as it as an UPDATE
> If the row does not exist -> leave the INSERT alone

There are some rather serious race conditions in that (it's not taking
anything like a strong enough lock to avoid that - it would need to use
SHARE ROW EXCLUSIVE, not ROW EXCLUSIVE).

In 8.0 on, use the method described here:
http://www.postgresql.org/docs/current/static/plpgsql-control-structures.html#PLPGSQL-ERROR-TRAPPING

--
Andrew, Supernews
http://www.supernews.com - individual and corporate NNTP services

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Peter Alberer 2006-01-03 10:24:57 Problem restoring db-dump on Postgres 8.0.4 Power5
Previous Message Tony Wasson 2006-01-03 06:02:56 Re: INSERT OR UPDATE