10

I need to check if a row exists or not. If it does not exist, it should be inserted.

This is in postgres and I am trying to insert row through a shell script. When I run the script it does not show error but it does not insert into table even though no matching row is present.

6
  • 6
    Please post the script you are using and the statement you are using to test if there is "no matching row". Commented Mar 4, 2013 at 15:08
  • 1
    See this link stackoverflow.com/questions/4555966/… Commented Mar 4, 2013 at 15:09
  • if you can use Ruby as your scripting language, you might try Upsert Commented Mar 4, 2013 at 17:58
  • 4
    I'm upset (not to be confused with upsert) that many of you have disregarded the distinction between insert-if-not-exists (asked by this question) and upsert (asked by the erroneously-marked duplicate question). Commented Mar 14, 2014 at 14:55
  • 1
    This is not a duplicate of the linked question; its answers aren't exactly applicable here. It may be a duplicate of a different question. Commented Aug 11, 2014 at 4:04

1 Answer 1

28

I like the solution they mention here

INSERT INTO table (id, field, field2)
       SELECT 3, 'C', 'Z'
       WHERE NOT EXISTS (SELECT 1 FROM table WHERE id=3);
Sign up to request clarification or add additional context in comments.

4 Comments

I tried this solution and it is not working as have a lower version. Hence, I wanted to split both of them into two different queries.
Postgres also now has an Upsert command where you can insert OR update a row: wiki.postgresql.org/wiki/UPSERT
On 9.5+, INSERT ... ON CONFLICT DO NOTHING or INSERT ... ON CONFLICT UPDATE stackoverflow.com/a/17267423/1386245
@Rohmer note: rohmer's solution only works if you have a constraint on the table

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.