Re: Doing a conditional insert/update

From: Rodrigo De León <rdeleonp(at)gmail(dot)com>
To: pgsql-sql(at)postgresql(dot)org
Cc: "Markus Holzer" <holli(dot)holzer(at)googlemail(dot)com>
Subject: Re: Doing a conditional insert/update
Date: 2007-04-19 18:58:59
Message-ID: a55915760704191158l278c760bg3b95296535a79e07@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On 4/19/07, Markus Holzer <holli(dot)holzer(at)googlemail(dot)com> wrote:
> Hello.
>
> I'm currently developing my first web app with Postgres and I have a
> question.
>
> How do I perform a conditional insert/update?
>
> To clarify: I need to insert data into a table when the primary key is not
> already in the table, or an update if it is. I have currently solved this by
> SELECTing for the primary key, then looking if there is a row, and if there
> is I do an UPDATE otherwise I do an INSERT. But since this is a web app this
> way of course leaves a big race condition.
>
> Is there a way to get around that? Like the ON DUPLICATE KEY UPDATE
> statement in MySQL?
>
>
> Thanks for your time,
>
> Holli

--------------------------------------------------

CREATE TABLE db (a INT PRIMARY KEY, b TEXT);

CREATE FUNCTION merge_db(key INT, data TEXT) RETURNS VOID AS
$$
BEGIN
LOOP
UPDATE db SET b = data WHERE a = key;
IF found THEN
RETURN;
END IF;

BEGIN
INSERT INTO db(a,b) VALUES (key, data);
RETURN;
EXCEPTION WHEN unique_violation THEN
-- do nothing
END;
END LOOP;
END;
$$
LANGUAGE plpgsql;

SELECT merge_db(1, 'david');
SELECT merge_db(1, 'dennis');

--------------------------------------------------

Straight from the docs:

http://www.postgresql.org/docs/8.2/static/plpgsql-control-structures.html#PLPGSQL-ERROR-TRAPPING

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Phillip Smith 2007-04-19 22:52:00 Re: slowness when subselect uses DISTINCT
Previous Message Andrew Sullivan 2007-04-19 18:55:21 Re: Doing a conditional insert/update