Re: insert or update within transaction

From: Josh Kupershmidt <schmiddy(at)gmail(dot)com>
To: Andreas <maps(dot)on(at)gmx(dot)net>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: insert or update within transaction
Date: 2011-09-17 15:49:49
Message-ID: CAK3UJRG6x9p2gmq7oxuDhO3mBqYrb7u1jsoaNBmyW_583kEZWw@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On Sat, Sep 17, 2011 at 10:52 AM, Andreas <maps(dot)on(at)gmx(dot)net> wrote:
> 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?

Yes, and that is indeed what I see when I run your example SQL. At the
end, I see this:

test=# SELECT * FROM tbl;
key | val
-----+-----
1 | 1
2 | 2
3 | 3
8 | 15
(4 rows)

(i.e. the row with "key" = 8 got updated, settings its "val" = 15)

> 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?

Sounds like you're looking for the MERGE statement, which doesn't
exist in PostgreSQL yet. You might want to check out:
http://www.postgresql.org/docs/current/static/plpgsql-control-structures.html#PLPGSQL-UPSERT-EXAMPLE

Josh

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Guillaume Lelarge 2011-09-17 15:51:10 Re: Use select and update together
Previous Message Andreas 2011-09-17 14:56:56 Re: Use select and update together