Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop table if exists in PostgreSQL database

Tags:

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.

like image 298
Sarfaraz Makandar Avatar asked Jun 30 '14 11:06

Sarfaraz Makandar


People also ask

What is DROP TABLE if exists?

Description. The DROP TABLE statement deletes the specified table, and any data associated with it, from the database. The IF EXISTS clause allows the statement to succeed even if the specified tables does not exist.

What is drop cascade in PostgreSQL?

The CASCADE option allows you to remove the table and its dependent objects. The RESTRICT option rejects the removal if there is any object depends on the table. The RESTRICT option is the default if you don't explicitly specify it in the DROP TABLE statement.

How do you drop a table in pgAdmin?

Open your pgAdmin and then go the object tree where we will go to the database and then move to the public section under schemas and then select the Employee table which we want to delete or drop. The drop table popup window will appear on the screen, where we will click on the Yes button to drop the Employee table.

Can we drop a table that has dependent views on it?

However, to drop a table that is referenced by a view or a foreign-key constraint of another table, CASCADE must be specified. ( CASCADE will remove a dependent view entirely, but in the foreign-key case it will only remove the foreign-key constraint, not the other table entirely.)


1 Answers

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).

like image 92
harmic Avatar answered Sep 21 '22 06:09

harmic