0

I have read the PostgreSQL control structure page and I decided to make a test:

IF 1 = 0 THEN
    INSERT INTO my_table (num_a, num_b)
    VALUES (1, 1);
END IF;

I have tested the insert statement alone and it works fine. But when I run the above code in psql I get:

ERROR:  syntax error at or near "IF" 
LINE 1: END IF;
            ^

What is wrong with it?

3
  • Post the whole function, as you've almost certainly an error before that line which is making the parser dizzy. Commented Jun 12, 2013 at 15:13
  • @Denis, that is the whole function. That's the only lines I'm executing. Commented Jun 12, 2013 at 15:14
  • You can't execute an if without a function (or at least a DO block) Commented Jun 12, 2013 at 15:16

1 Answer 1

4

Per your comment, you're probably missing a do block:

http://www.postgresql.org/docs/current/static/sql-do.html

DO $$
BEGIN
  IF 1 = 0 THEN
    INSERT INTO my_table (num_a, num_b)
    VALUES (1, 1);
  END IF;
END;
$$ language plpgsql;

Or put it into a function.

Sign up to request clarification or add additional context in comments.

5 Comments

Seems to be working. Gotta test this out a bit. Isn't there a way to do this in pure SQL?
No, there isn't any means to do this kind of stuff out of a procedural language in Postgres. The docs page you were pointing to, by the way, was about plpgsql -- one of many procedural languages.
What is it you actually want to do in pure SQL? Because this sample code actually does nothing, since 1 != 0. You can do CASE statements on results or WHERE clauses to limit what you insert in a table... INSERT INTO MYTABLE (1,1) WHERE 1=0 for pseudo-example.
@Chipmonkey, I want to execute an insert statement only if a certain condition (calculated with a subquery) is met. The 1 = 0 part was just for testing.
But what do you want to do if the subquery condition is not met? If nothing then I still think "INSERT INTO MYTABLE (1,1) WHERE (SELECT HIGHLY COMPLICATED SUBQUERY)" is completely valid. You may need "WHERE EXISTS" or an "IS NOT NULL" somewhere. You can google "correlated subquery" if you need values from MYTABLE in the subquery, all in pure SQL. I understand the 0=1 placeholder, but more specifics may help if you still want a pure sql solution.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.