Remove all tables in a Postgres schema

Tables in a data model

When working with initial migrations in a project it is often helpful to fast clear all tables and then re-run all migrations. Instead of removing och re-creating the schema (which will affect everything besides just tables), you can use this script taken from this SO answer.

1DO $$ DECLARE 2 r RECORD; 3BEGIN 4 -- if the schema you operate on is not "current", you will want to 5 -- replace current_schema() in query with 'schematodeletetablesfrom' 6 -- *and* update the generate 'DROP...' accordingly. 7 FOR r IN (SELECT tablename FROM pg_tables WHERE schemaname = current_schema()) LOOP 8 EXECUTE 'DROP TABLE IF EXISTS ' || quote_ident(r.tablename) || ' CASCADE'; 9 END LOOP; 10END $$;