It is possible to "reset" the public schema in a PostgreSQL database using SQL. This can be achieved in two main ways, depending on whether you want to drop the entire schema or just the tables within it.
This method removes all objects within the schema—tables, views, sequences, etc.—and then recreates it.
DROP SCHEMA public CASCADE; -- Drops the public schema and all contained objects
CREATE SCHEMA public; -- Recreates the public schema
GRANT ALL ON SCHEMA public TO postgres; -- Restore default permissions
GRANT ALL ON SCHEMA public TO public;DROP SCHEMA public CASCADE;: Deletes the schema and all objects inside it.CREATE SCHEMA public;: Recreates a cleanpublicschema.GRANTstatements: Restore default access permissions.
✅ Use this method if you want a complete reset of the schema.
This method retains non-table objects (e.g., views, functions) while removing only the tables.
DO $$
DECLARE
r RECORD;
BEGIN
FOR r IN (SELECT tablename FROM pg_tables WHERE schemaname = 'public') LOOP
EXECUTE 'DROP TABLE IF EXISTS ' || quote_ident(r.tablename) || ' CASCADE';
END LOOP;
END $$;- Iterates over all tables in the
publicschema. - Dynamically drops each table using
EXECUTE. CASCADEensures dependent objects (e.g., foreign keys) are removed too.
✅ Use this method if you want to preserve non-table objects in the schema.
- Backup Data: Both methods are destructive. Back up any needed data before proceeding.
- Permissions: Ensure permissions are correctly restored after recreating the schema.
- Dependencies: Use
CASCADEcautiously to automatically handle dependencies.
| Goal | Recommended Method |
|---|---|
| Full schema reset | Method 1: Drop & Recreate Schema |
| Remove tables only | Method 2: Drop Only Tables |
This gist was generated with the help of ChatGPT based on information provided and saved by the user.