IF and other PL/pgSQL features are only available inside PL/pgSQL functions. You need to wrap your code in a function if you want to use IF. If you’re using 9.0+ then you can do use DO to write an inline function:
do $$
begin
-- code goes here
end
$$
If you’re using an earlier version of PostgreSQL then you’ll have to write a named function which contains your code and then execute that function.