Re: automatic update or insert

Поиск
Список
Период
Сортировка
От PFC
Тема Re: automatic update or insert
Дата
Msg-id op.sy6zi1w0th1vuj@localhost
обсуждение исходный текст
Ответ на automatic update or insert  ("tobbe" <tobbe@tripnet.se>)
Список 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 по дате отправления:

Предыдущее
От: "Marc G. Fournier"
Дата:
Сообщение: convert timezone to string ...
Следующее
От: "Magnus Hagander"
Дата:
Сообщение: Re: convert timezone to string ...