9

How do I delete all the tables I have in a specific schema? Only the tables in the schema should be deleted. I already have all the table names that I fetched with the code below, but how do delete all those tables?

The following is some psycopg2 code, and below that is the SQL generated

writeCon.execute("SELECT table_name FROM information_schema.tables WHERE table_schema='mySchema'")

SELECT table_name FROM information_schema.tables WHERE table_schema='mySchema'

1

2 Answers 2

15

You can use an anonymous code block for that.

WARNING: This code is playing with DROP TABLE statements, and they are really mean if you make a mistake ;) The CASCADE option drops all depending objects as well. Use it with care!

DO $$
DECLARE
  row record;
BEGIN
    FOR row IN SELECT * FROM pg_tables WHERE schemaname = 'mySchema' 
    LOOP
      EXECUTE 'DROP TABLE mySchema.' || quote_ident(row.tablename) || ' CASCADE';
    END LOOP;
END;
$$;

In case you want to drop everything in your schema, including wrappers, sequences, etc., consider dropping the schema itself and creating it again:

DROP SCHEMA mySchema CASCADE;
CREATE SCHEMA mySchema;
Sign up to request clarification or add additional context in comments.

7 Comments

I am sure how to call such statements with psycopg2, unfortunately.
what happens if you pass this code inside the writeCon.execute() function?e.g. writeCon.execute("DO $$ DECLARE row record; BEGIN FOR row IN SELECT * FROM pg_tables WHERE schemaname = 'mySchema' LOOP EXECUTE 'DROP TABLE mySchema.' || quote_ident(row.tablename); END LOOP; END; $$;")
it says that I need to add a Cascade because there are some dependencies. Where do I add that?
@GoldenRetriever try adding a CASCADE to the drop table statement: DROP TABLE mySchema.' || quote_ident(row.tablename) CASCADE;
Error: psycopg2.errors.SyntaxError: syntax error at or near "CASCADE" LINE 3: 'mySchema.' || quote_ident(row.tablename) CASCADE; E...
|
5

For a single-line command, you can use psql and its \gexec functionality:

SELECT format('DROP TABLE %I.%I', table_schema, table_name)
FROM information_schema.tables
WHERE table_schema= 'mySchema';\gexec

That will run the query and execute each result string as SQL command.

5 Comments

What is \gexec ?
@GoldenRetriever see the doc
Invalid command \gexec. Try \? for help.
@RaulChiarella it seems you have added an extra . after the command.
No dot. Just copied pasted exactly as it is, it is postgres that adds the dot.

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.