7

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

I was able to select form system table to find out if there any table with such a name but stuck with procedural part:

SELECT count(*) FROM pg_tables where tablename='user_statistics';

2 Answers 2

16
DROP TABLE user_statistics;

DROP VIEW user_statistics;

complete syntax:

DROP TABLE

DROP VIEW

And if you want a complete 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;
Sign up to request clarification or add additional context in comments.

Comments

-4

Consider using DROP TABLE IF EXISTS and DROP VIEW IF EXISTS. That way you won't get an error message if it fails, just a notice.

2 Comments

That won't work actually. If you're doing DROP VIEW IF EXISTS and the view that you are trying to drop is actually a table than Postgres will give you an error that it is not a view (the same goes for DROP TABLE IF EXISTS). You need to know for sure if it's a table or a view.
DROP TABLE IF EXISTS name_of_table - to be precise

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.