[PyGreSQL] How to insert a record if it doesn't exist else update it ?

Daryl Tester dt-pygresql at handcraftedcomputers.com.au
Thu Dec 20 14:45:05 EST 2007


fdu.xiaojf at gmail.com wrote:

> What I want to do is:
>      if a record already exists in the table, update it
>      if a record doesn't exist, insert it into the table

UPDATE foo SET ...
   WHERE EXISTS (SELECT 1 FROM foo ...);

INSERT INTO foo
   SELECT ... FROM ... WHERE NOT EXISTS (SELECT 1 FROM foo ...);

The 2nd statement is executed if the first is false.  Not race-proof,
and can't be, even with transactions, so be sure to execute it in a
sequential manner.


-- 
Regards,
  Daryl Tester

"Verbogeny is one of the pleasurettes of a creatific thinkerizer."
  --  Peter da Silva


More information about the PyGreSQL mailing list