I’m having a reoccurring error in my SQL statement, and I cannot figure out how to fix it.
The ERROR: syntax error at or near "WHERE"
is not very helpful as well.
This is the code snippet in question:
INSERT INTO example.table (first, second, third, fourth, fifth)
(SELECT first,second,third,fourth,'constant'
FROM example.table
WHERE some_id=42)
WHERE NOT EXISTS
(SELECT 1
FROM example.table
WHERE (first,third,status)=(SELECT first,third,'request' FROM example.table
WHERE some_id=42));
Everything works as intended up until the ‘WHERE NOT EXISTS’, but everything also works if I replace the second line with just values instead of searching them from the table.
How can I fix this code?
Thanks a lot!
2
Answers
Perhaps
There can only be one
WHERE
clause per DML command, as the syntax error indicates.But I am also pretty sure you don’t want to introduce a 4th (uncorrelated!) instance of
example.table
in theEXISTS
subquery. That would exclude rows based on any row withsome_id=42
, while you most certainly want to just base that on the row at hand.So refer back to the instance you are selecting from.
Related: