Re: automatic update or insert - Mailing list pgsql-sql

From PFC
Subject Re: automatic update or insert
Date
Msg-id op.sy6zi1w0th1vuj@localhost
Whole thread Raw
In response to automatic update or insert  ("tobbe" <tobbe@tripnet.se>)
List 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.


pgsql-sql by date:

Previous
From: "Marc G. Fournier"
Date:
Subject: convert timezone to string ...
Next
From: "Magnus Hagander"
Date:
Subject: Re: convert timezone to string ...