insert or update within transaction

From: Andreas <maps(dot)on(at)gmx(dot)net>
To: pgsql-sql(at)postgresql(dot)org
Subject: insert or update within transaction
Date: 2011-09-17 14:52:55
Message-ID: 4E74B447.1080509@gmx.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Hi,
http://www.postgresql.org/docs/current/static/sql-update.html
has an example where an either an insert or update is done according if
a key already exists.
The example is about wines. I did it with numbers.

drop table if exists tbl;
create table tbl ( key int primary key, val int );
insert into tbl ( key, val ) values ( 1, 1 ), ( 2, 2 ), ( 3, 3 ), ( 8, 8 );

So the key 8 exists.
Now I issue the commands according to the example in the docu:

BEGIN;
-- other operations
SAVEPOINT sp1;
INSERT INTO tbl VALUES( 8, 15 );
-- Assume the above fails because of a unique key violation,
-- so now we issue these commands:
ROLLBACK TO sp1;
UPDATE tbl SET val = 15 WHERE key = 8;
-- continue with other operations, and eventually
COMMIT;

Instead of the update the query fails with an double key value error for
the primary key.
Shouldn't the insert fail, get rolled back and then exercute an update
instead successfully?

Now if this actually worked would be nice but is there a more general
statement that does an insert if the key doesn't exist or an update if
it allready is there?
As I understand if the example above worked, it rolled back the insert
in any case and so it is actually equivalent to the update anyway.
If the key 8 doesnt't exist the example does actually nothing to the table.

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Andreas 2011-09-17 14:56:56 Re: Use select and update together
Previous Message David Johnston 2011-09-17 13:56:46 Re: Sorting of data from two tables