There are two ways in which we can drop all the tables in a PostgreSQL database.
In a database, a schema is an object container where the objects can be tables, data types, functions, or operators.
For more information on database schemas, you can look at this Answer.
Dropping a schema will remove the tables contained in that schema. However, the schema and its permission need to be re-created.
Let’s make the schema name public
. The SQL statements to drop a schema are as follows:
DROP SCHEMA public CASCADE;
CREATE SCHEMA public;
GRANT ALL ON SCHEMA public TO postgres;
GRANT ALL ON SCHEMA public TO public;
DROP SCHEMA
statement.public
schema using the CREATE SCHEMA
statement.public
schema to users postgres
and public
.This method of deleting the tables from a database is a bit risky, which makes it unsuitable for development.
In this method, we get all the tables in a schema and delete the tables individually using the DROP TABLE
command. This method is suitable for the production environment, as other objects in the schema are retained.
PostgreSQL stores all the tables and the table metadata on its record table called pg_table
.
The query is as follows:
SELECT
'DROP TABLE IF EXISTS "' || tablename || '" CASCADE;'
from
pg_tables WHERE schemaname = 'public';
We select all the tables from pg_tables
whose schemaname
is public
. Using subquery, we delete the tables from the schema.