Follow dba-ninja.com

Subscribe to RSS feed  Follow @jackvamvas - Twitter

*Use the Comments section for questions

dba-ninja.com Links

Dba_db2_button

Sqlserver_dba_button

How to drop all tables in a schema in PostgreSQL?

06 March,2023 by Rambler

Question: How to drop all tables from a PostgreSQL database schema?

 

Answer: If you have a requirement to drop all from a PostgreSQL database schema this code snippet will allow you to a) create the DROP statements and 2) execute the DROP statements. 

It is best paractise to have a backup in place before proceeding with this activity . If you're intention is to run this on a Production , I strongly recommend all statements are tested in a lower environment to extablish any unforeseen results.

NOTE: This output includes CASCADE option with the DROP TABLE command will drop a table along with its dependent objects

 

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


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

Executing this statement will generate list of  DROP statements - use those DROP statements to drop all tables for a specific schema.

Read more on PostgreSQL

How to create a PostgreSQL user for CRUD

How to change PostgreSQL default schema

How to change PostgreSQL database data directory


Author: Rambler (http://www.dba-ninja.com)


Share:

Verify your Comment

Previewing your Comment

This is only a preview. Your comment has not yet been posted.

Working...
Your comment could not be posted. Error type:
Your comment has been posted. Post another comment

The letters and numbers you entered did not match the image. Please try again.

As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.

Having trouble reading this image? View an alternate.

Working...

Post a comment on How to drop all tables in a schema in PostgreSQL?


dba-ninja.com