From: | Jasen Betts <jasen(at)xnet(dot)co(dot)nz> |
---|---|
To: | pgsql-general(at)postgresql(dot)org |
Subject: | Re: Easy form of "insert if it isn't already there"? |
Date: | 2012-02-19 07:31:13 |
Message-ID: | jhq8g1$17h$1@reversiblemaps.ath.cx |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-general |
On 2012-02-15, Chris Angelico <rosuav(at)gmail(dot)com> wrote:
> Periodically I find myself wanting to insert into some table,
> specifying the primary key column(s), but to simply ignore the request
> if it's already there. Currently I have two options:
>
> 1) Do the insert as normal, but suppress errors.
> SAVEPOINT foo;
> INSERT INTO table (col1,col2,col3) VALUES (val1,val2,val3);
> (if error) ROLLBACK TO SAVEPOINT foo;
>
> 2) Use INSERT... SELECT:
> INSERT INTO table (col1,col2,col3) SELECT val1,val2,val3 WHERE NOT
> EXISTS (SELECT * FROM table WHERE col1=val1 AND col2=val2)
>
> The former makes unnecessary log entries, the latter feels clunky. Is
> there some better way?
neither of those work all of the time.
It's not until the transaction is committed that you can know that it
was successful (ignoring 3-phase for the sake of clarity)
the best way is probably method 2 but remember to handle the errors
that you will still get sometimes.
--
⚂⚃ 100% natural
From | Date | Subject | |
---|---|---|---|
Next Message | Jasen Betts | 2012-02-19 07:37:40 | Re: Fwd: Re: Dynamic update of a date field |
Previous Message | Jasen Betts | 2012-02-19 04:14:14 | Re: Backup database remotely |