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;
7
  • I am sure how to call such statements with psycopg2, unfortunately. Commented Jan 14, 2020 at 14:31
  • 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; $$;")
    – Jim Jones
    Commented Jan 14, 2020 at 15:36
  • it says that I need to add a Cascade because there are some dependencies. Where do I add that? Commented Jan 14, 2020 at 15:46
  • @GoldenRetriever try adding a CASCADE to the drop table statement: DROP TABLE mySchema.' || quote_ident(row.tablename) CASCADE;
    – Jim Jones
    Commented Jan 14, 2020 at 15:47
  • Error: psycopg2.errors.SyntaxError: syntax error at or near "CASCADE" LINE 3: 'mySchema.' || quote_ident(row.tablename) CASCADE; E... Commented Jan 14, 2020 at 15:51
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
  • What is \gexec ? Commented Jan 14, 2020 at 8:53
  • @GoldenRetriever see the doc
    – JGH
    Commented Jan 14, 2020 at 12:04
  • Invalid command \gexec. Try \? for help. Commented Aug 30, 2022 at 16:17
  • @RaulChiarella it seems you have added an extra . after the command.
    – JGH
    Commented Aug 30, 2022 at 17:42
  • No dot. Just copied pasted exactly as it is, it is postgres that adds the dot. Commented Aug 30, 2022 at 17:44

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.