DEV Community

Andreas Bergström
Andreas Bergström

Posted on • Updated on

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.

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

Top comments (0)