How to delete a table * or * from a PostgreSQL database?

I have the name of a table or view in a PostgreSQL database and need to delete it in one pgSQL command. How can I afford it?

I managed to select the system form table to find out if there is a table with that name, but got stuck with the procedural part:

SELECT count(*) FROM pg_tables where tablename='user_statistics'; 
+4
source share
2 answers
 DROP TABLE user_statistics; DROP VIEW user_statistics; 

full syntax:

DROP TABLE

DROP VIEW

And if you want to get the full function, I tried something like this:

 CREATE OR REPLACE FUNCTION delete_table_or_view(objectName varchar) RETURNS integer AS $$ DECLARE isTable integer; isView integer; BEGIN SELECT INTO isTable count(*) FROM pg_tables where tablename=objectName; SELECT INTO isView count(*) FROM pg_views where viewname=objectName; IF isTable = 1 THEN execute 'DROP TABLE ' || objectName; RETURN 1; END IF; IF isView = 1 THEN execute 'DROP VIEW ' || objectName; RETURN 2; END IF; RETURN 0; END; $$ LANGUAGE plpgsql; 
+11
source

Consider the use of DROP TABLE IF EXISTS and DROP VIEW IF EXISTS. This way you will not receive an error message if it does not work, just a notification.

-4
source

All Articles