Reputation:
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?
Upvotes: 10
Views: 56958
Reputation: 9418
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$$;
Upvotes: 1
Reputation: 45795
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.
Upvotes: 18
Reputation: 62573
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
.
Upvotes: 5