Re: MERGE vs REPLACE

From: Dennis Bjorklund <db(at)zigo(dot)dhs(dot)org>
To: Bruce Momjian <pgman(at)candle(dot)pha(dot)pa(dot)us>
Cc: Zeugswetter Andreas DCP SD <ZeugswetterA(at)spardat(dot)at>, Csaba Nagy <nagy(at)ecircle-ag(dot)com>, Martijn van Oosterhout <kleptog(at)svana(dot)org>, Dann Corbit <DCorbit(at)connx(dot)com>, Simon Riggs <simon(at)2ndquadrant(dot)com>, Rick Gigger <rick(at)alpinenetworking(dot)com>, Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>, Christopher Kings-Lynne <chriskl(at)familyhealth(dot)com(dot)au>, "Jim C(dot) Nasby" <jnasby(at)pervasive(dot)com>, <josh(at)agliodbs(dot)com>, <pgsql-hackers(at)postgresql(dot)org>, Jaime Casanova <systemguards(at)gmail(dot)com>, Peter Eisentraut <peter_e(at)gmx(dot)net>
Subject: Re: MERGE vs REPLACE
Date: 2005-11-18 04:57:05
Message-ID: Pine.LNX.4.44.0511180542100.17602-100000@zigo.dhs.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

On Thu, 17 Nov 2005, Bruce Momjian wrote:

> Unless you have a table lock, INSERT has to be before UPDATE, think
> UPDATE, UPDATE (both fail), INSERT, INSERT.

No matter what operation you start with you need a loop that try
insert/update until one of them succeed like in this example:

http://www.postgresql.org/docs/8.1/static/plpgsql-control-structures.html#PLPGSQL-UPSERT-EXAMPLE

Without a loop you might not get to execute neither the insert nor the
update. Why? Think about this example:

BEGIN

INSERT <- fail because there is a row already

<- before we manage to do the update someone
delete the row (which we can see in the
default transaction isolation level)

UPDATE <- fail because there is no row so we will loop
and try the insert again

<- before we manage to do the insert someone else does
an insert

INSERT <- fail because there is a row already

<- before we manage to do the update someone
delete the row
....

You might need to loop any number of times before you manage to perform
one of the two operations. Which operation you should start with depends
on which of the two cases is the common one.

--
/Dennis Björklund

In response to

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Jim C. Nasby 2005-11-18 05:15:32 Loading 7.4 dump to 8.1 with user-custom search_path breaks
Previous Message Jonah H. Harris 2005-11-18 04:45:16 Re: CLUSTER and clustered indices