10

Why do I always get the following error from Postgres?

syntax error at or near "IF"

I read PostgreSQL: Documentation: 8.3: Control Structures. First I tried to execute a difficult query (with subquery), but then I tried to execute a simple one like this:

IF 2 <> 0 THEN select * from users; END IF;

The error is still the same. What am I doing wrong?

0

3 Answers 3

18
IF 2 <> 0 THEN select * from users; END IF;

You cannot use PL/pgSQL statements outside plpgsql functions. And if this fragment is from plpgsql function, then it is nonsense too. You cannot directly return result of query like T-SQL does.

CREATE OR REPLACE FUNCTION test(p int)
RETURNS SETOF users AS $$
BEGIN
  IF p = 1 THEN
    RETURN QUERY SELECT * FROM users;
  END IF;
  RETURN;
END;
$$ LANGUAGE plpgsql;

When you would get some result from function, you have to use RETURN statement - plpgsql knows only function, it doesn't support procedures - so unbounded SELECT has not sense.

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

2 Comments

Oh, thanks for your reply too. No i just was searching on how to make one or another "select" depending on condition in "IF". So as i found there is no way to do it in simple like this IF (SELECT ...) = 2 THEN SELECT... ELSE SELECT ... END IF;
Actually IF (select a from t) = 2 THEN NULL; END IF; would work, the problem is probably that you are trying to SELECT something in a context, that does not return anything. In this case Pavel made a perfect example. You can use RETURN QUERY taking into account, that you defined your function correctly.
5

You're not enclosing that PL/pgSQL control structure in an anonymous block or a PL/pgSQL function.

For the SQL version of this control structure see the docs for CASE.

1 Comment

CASE cannot be used at the top-level, though, only as a part of a SQL query. In other words, it cannot be used to direct behavior that isn't a part of another query already, which is what the original question seemed to want.
1

You're not enclosing that PL/pgSQL. They need to be enclosed with anonymous code block. Example for your code:

DO $$ BEGIN

    IF 2 <> 0 THEN select * from users; END IF;

END$$;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.