Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WHERE NOT EXISTS in PostgreSQL gives syntax error

When trying to use the WHERE NOT EXISTS clause to prevent adding a row with a duplicate value in the column age, I get the error syntax error at or near "WHERE".

Why did it throw a syntax error? I'm using Postgresql 9.1.

SQL

INSERT INTO live.users ("website", "age") 
values ('abc', '123')
WHERE NOT EXISTS (SELECT age FROM live.users WHERE age = 123);

Error

ERROR:  syntax error at or near "WHERE"
LINE 6: WHERE NOT EXISTS (SELECT age FROM live.users W...
like image 801
Nyxynyx Avatar asked Apr 05 '13 18:04

Nyxynyx


2 Answers

Do instead:

INSERT INTO live.users ("website", "age") 
SELECT 'abc', 123
WHERE NOT EXISTS (SELECT age FROM live.users WHERE age = 123);
like image 113
Daniel Vérité Avatar answered Nov 08 '22 09:11

Daniel Vérité


INSERT INTO live.users ("website", "age") 
select 'abc', '123'
WHERE NOT EXISTS (SELECT age FROM live.users WHERE age = 123);
like image 3
Clodoaldo Neto Avatar answered Nov 08 '22 10:11

Clodoaldo Neto