May 10, 2011, 9:54 p.m.
IT

Conditional inserts in PostgreSQL

I have many times wanted to perform the following kind of SQL statement:

insert into X (field1, field2) values (A,B) if not exists X.field1 = A

The idea is to have a single statement that only inserts the value if a given key (in this case A) does not already exist. Therefore it is like a unique add operation. To implement this in PostgreSQL, simply do:

insert into X (field1, field2) select A, B where not exists
   (select field1 from X where field1 = A)

Neat, hey?