8

I want to check whether the table exists or not in the database.

IF NOT EXISTS (SELECT * from INFORMATION_SCHEMA.Tables WHERE Table_name = 'test') THEN

    RAISE INFO 'Not exists';

else

    RAISE INFO 'Exists';

end if;

Getting an error:

ERROR:  syntax error at or near "IF"
MAK
  • 6,824
  • 25
  • 74
  • 131

2 Answers2

10
DO
$do$
BEGIN
IF NOT EXISTS (SELECT * from INFORMATION_SCHEMA.Tables WHERE Table_name = 'test') THEN

    RAISE INFO 'Not exists';

else

    RAISE INFO 'Exists';

end if;
end;
$do$

You should surround your postgresql statements with block

DAlekperov
  • 141
  • 5
0

IF NOT EXISTS is not valid in that context within (what appears like) plpgsql.

It can be used in contexts like CREATE TABLE IF NOT EXISTS foo.

In a plpgsql context, you should use GET DIAGNOSTICS combined with ROW_COUNT.

The doc gives the following code snippet for that:

GET DIAGNOSTICS integer_var = ROW_COUNT;

If integer_var (which you will need to have previously declared) is 0, you know that the table doesn't exist.

See the Postgres doc for more details.

khampson
  • 14,700
  • 4
  • 41
  • 43