I'm having trouble figuring out how to insert a row in a table exclusively if a specific condition is true using Postgres.
I've found a lot of answers that use CONFLICT
, but the value I'm checking for isn't unique, so I can't do much with that. I've also tried IF
ELSE
but as far as I understand it Postgres doesn't support this?
This is my current query:
IF EXISTS (SELECT id FROM "Vote" as v WHERE v."createdAt" >= '2020-09-01' AND v."createdAt" < '2020-10-01' AND v."authorId" = 6667 )
PRINT 'do nothing'
ELSE
INSERT INTO "Vote" ("authorId", "serverId") VALUES (1, 1);
It returns:
ERROR: syntax error at or near "IF"
Essentially I'm checking if a user has cast a vote between two dates, if that is true, then nothing should happen, if false the vote should be inserted in the table.
Is checking if something should be inserted and inserting it possible in a single query, or should I first check if the value exists and then run the insert query?