javaGirl
javaGirl

Reputation: 195

Syntax error at or near "IF" PostgreSQL

I am trying to use subselect in my code but it gives me an error. I have found a lot of solution but it still does not work:

Here is my code:

BEGIN;
IF (SELECT COUNT(*) FROM table1 WHERE Z = 'aaaaa') = 0

    THEN
    INSERT INTO table2 (X, Y) VALUES ("abc", 7)

END IF;
END;

and error:

ERROR:  syntax error at or near "IF"
LINE 2: IF (SELECT COUNT(*) FROM table1 WHERE Path = 'aaaaa') = 0
        ^


********** Error **********

ERROR: syntax error at or near "IF"
SQL state: 42601
Character: 8

Could you help me?

Upvotes: 3

Views: 9763

Answers (1)

araqnid
araqnid

Reputation: 133462

Drop the semicolon after "BEGIN"? That's if this is the body of a plpgsql function.

If this is a psql script, the IF statement needs to be given to plpgsql to execute, so it needs putting in a DO $$ ... $$ construct.

Or, of course, you could refactor like so:

INSERT INTO table2(x,y)
    SELECT 'abc', 7
    WHERE NOT EXISTS (SELECT 1 FROM table1 WHERE z = 'aaaaa')

Upvotes: 11

Related Questions