Easy form of "insert if it isn't already there"? - Mailing list pgsql-general

From Chris Angelico
Subject Easy form of "insert if it isn't already there"?
Date
Msg-id CAPTjJmrZHz6X1VnadY1WQytsRTVK4Z-auQaLeJZ29o0-Esg9kw@mail.gmail.com
Whole thread Raw
Responses Re: Easy form of "insert if it isn't already there"?  (Bartosz Dmytrak <bdmytrak@eranet.pl>)
List pgsql-general
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?

All tips appreciated!

Chris Angelico

pgsql-general by date:

Previous
From: Venkat Balaji
Date:
Subject: Re: [GENERA]: Postgresql-9.1.1 synchronous replication issue
Next
From: Venkat Balaji
Date:
Subject: Re: High checkpoint_segments