Re: automatic update or insert

From: PFC <lists(at)boutiquenumerique(dot)com>
To: tobbe <tobbe(at)tripnet(dot)se>, pgsql-sql(at)postgresql(dot)org
Subject: Re: automatic update or insert
Date: 2005-10-25 08:07:39
Message-ID: op.sy6zi1w0th1vuj@localhost
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql


> In a system of mine i need to insert records into table [tbStat], and
> if the records exist i need to update them instead and increase a
> column [cQuantity] for every update.
>
> I.e. the first insert sets cQuantity to 1, and for every other run
> cQuantity is increased.
>
> Currently i have implemented this as a stored procedure in the plpgsql
> language. This means that in my stored procedure i first do a select to
> find out if the row exists or not, then i do a insert or update
> depending if the row existed.

There are two ways you can do this :

* If you will have more updates than inserts (ie. more items with a
quantity >1 than 1) :

UPDATE
If the update updated no rows, then INSERT

* If you have more inserts than updates (ie. more items with quantity 1
than >1) :

INSERT
if it fails due to violating the unique constraint, then UPDATE

None of these involve a SELECT. The first one is very cheap if you end up
doing more updates than inserts, because it just does the update.

You will of course need a UNIQUE index to identify your rows, and prevent
insertion of duplicates. I suppose you have this already.
There is a subtility in the second form : the INSERT will fail on
duplicate key, so you have to either rollback the transaction if you send
the queries raw from your app, or catch the exception in your plpgsql
function.
Also a race condition might exist if someone deletes a row in-between, or
the first procedure is executed twice at the same time by different
threads. Be prepared to retry your transaction.

Something like the ON DUPLICATE KEY UPDATE in MySQL would be nice to have.

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Magnus Hagander 2005-10-25 11:03:19 Re: convert timezone to string ...
Previous Message Marc G. Fournier 2005-10-25 05:42:11 convert timezone to string ...