Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If a row does not exists insert else don't insert in postgres

Tags:

sql

postgresql

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.

like image 391
JumpOffBox Avatar asked Mar 04 '13 15:03

JumpOffBox


1 Answers

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);
like image 110
Andres Olarte Avatar answered Oct 30 '22 23:10

Andres Olarte