Skip to content
Advertisement

Insert values if records don’t already exist in Postgres

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'
  );

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement