Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert values if records don't already exist in Postgres

Tags:

sql

postgresql

I'd like to get this working, but Postgres doesn't like having the WHERE clause in this type of insert.

  INSERT INTO keys(name, value) VALUES
    ('blah', 'true')
  WHERE NOT EXISTS (
    SELECT 1 FROM keys WHERE name='blah'
  );
like image 282
Matt York Avatar asked Dec 17 '12 16:12

Matt York


2 Answers

In Postgres, there is a really nice way to do that:

INSERT INTO keys(name, value) 
    SELECT 'blah', 'true'
WHERE NOT EXISTS (
    SELECT 1 FROM keys WHERE name='blah'
);

hope that helps.-

like image 105
VoidMain Avatar answered Sep 28 '22 04:09

VoidMain


In Postgresql 9.5 you can now use on conflict do nothing

insert into KEYS (name, value) values (
'blah', 'true') on conflict (name) do nothing;
like image 43
MK Yung Avatar answered Sep 28 '22 05:09

MK Yung