Sarfaraz Makandar
Sarfaraz Makandar

Reputation: 6733

Drop table if exists in PostgreSQL database

I am trying to drop table if it is exists in the present working database of PostgreSQL. For which I am trying the following query.

Example:

var1 := 'IF EXISTS (select * from INFORMATION_SCHEMA.TABLES WHERE name = ''Table_'|| Suffix ||''') then
      DROP TABLE Table_'||Suffix||'';

execute var1;

But getting error near IF.

Upvotes: 28

Views: 38923

Answers (1)

harmic
harmic

Reputation: 30577

execute executes SQL statements, not PL/pgSQL commands. The IF statement is a PL/pgSQL construct.

In any case you can use

DROP TABLE IF EXISTS ...

(see the manual page for DROP).

Upvotes: 62

Related Questions