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" 
0

2 Answers 2

11
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

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

1 Comment

why this works?
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.