Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I drop all the tables in a PostgreSQL database?

Tags:

postgresql

How can I drop all tables in PostgreSQL, working from the command line?

I don't want to drop the database itself, just all tables and all the data in them.

like image 957
AP257 Avatar asked Jul 24 '10 23:07

AP257


People also ask

How do I drop multiple tables in PostgreSQL?

PostgreSQL DROP Multiple Tables You can remove multiple tables from a database in one statement in PostgreSQL by specifying the comma-separated name of the tables after the statement DROP TABLE. The syntax is as follow: DROP TABLE [IF EXISTS] table_name1, table_name2, ... ... ... table_nameN [CASCADE | RESTRICT];

Can I drop Postgres database?

The first method to remove a PostgreSQL database is to use the following SQL statement: DROP DATABASE <database name>; The command removes the directory containing the database information and the catalog entries. Only the database owner can execute the DROP DATABASE command.


2 Answers

If all of your tables are in a single schema, this approach could work (below code assumes that the name of your schema is public)

DROP SCHEMA public CASCADE; CREATE SCHEMA public; 

If you are using PostgreSQL 9.3 or greater, you may also need to restore the default grants.

GRANT ALL ON SCHEMA public TO postgres; GRANT ALL ON SCHEMA public TO public; 
like image 73
Derek Slife Avatar answered Oct 04 '22 12:10

Derek Slife


You can write a query to generate a SQL script like this:

select 'drop table "' || tablename || '" cascade;' from pg_tables; 

Or:

select 'drop table if exists "' || tablename || '" cascade;' from pg_tables; 

In case some tables are automatically dropped due to cascade option in a previous sentence.

Additionally, as stated in the comments, you might want to filter the tables you want to drop by schema name:

select 'drop table if exists "' || tablename || '" cascade;'    from pg_tables  where schemaname = 'public'; -- or any other schema 

And then run it.

Glorious COPY+PASTE will also work.

like image 23
Pablo Santa Cruz Avatar answered Oct 04 '22 11:10

Pablo Santa Cruz