PostgreSQL – How to Drop All Tables of a Schema
To drop all tables in a PostgreSQL schema, you can use SQL queries or a combination of SQL queries and shell scripting.
- Connect to your PostgreSQL database using a PostgreSQL client such as
psql
. - Run the following SQL query to generate a list of
DROP TABLE
statements for all tables in a specific schema; In the below query,your_schema_name
is the name of the schema you want to drop tables from:
SELECT 'DROP TABLE IF EXISTS "' || schemaname || '"."' || tablename || '" CASCADE;' FROM pg_tables WHERE schemaname = 'your_schema_name';
- This query will generate a list of
DROP TABLE
statements for all tables in the specified schema, including any dependent objects. Be sure to review the list to ensure you want to delete all these tables. - Once you are sure, you can copy the generated
DROP TABLE
statements and paste them into your PostgreSQL client to execute them, which will drop all the tables in the schema.