33

I want to drop all of the databases except few ones. Lets say there are 20 databases and I want to delete 18 out of them but keep 2 as it is the latest ones and are in use.

Please suggest.

4
  • "drop database databasename" for your deletable 18 databases.. Commented Jul 3, 2014 at 8:10
  • Thanks for quick reply! I want a single script where I would like to mention only the 2 databases names which I want to keep. Commented Jul 3, 2014 at 8:12
  • @user3800715 ... and when you tried to write this script yourself, using the scripting language of your choice, where did you get stuck? Commented Jul 3, 2014 at 8:16
  • @CraigRinger I am not sure how to write the script for this query. Can someone provide a script for the same compatible to postgres? Commented Jul 3, 2014 at 8:21

3 Answers 3

65

First, execute the following query in the psql terminal.

select 'drop database "'||datname||'";'
from pg_database
where datistemplate=false;

This will generate drop database command for all the databases. Copy the result in a text editor and exclude(delete) what you want to keep and save it as dd.sql file. And execute it like this:

psql -d postgres -f dd.sql
Sign up to request clarification or add additional context in comments.

1 Comment

optionally: psql -d postgres < <( psql -Atc "select 'drop database \"'||datname||'\";' from pg_database where datistemplate=false /* AND add_extra_conditions_here */;")
14

From pgAdmin you can now select properties on a database, select DBs to drop and click delete/drop. Quick and easy! Drop selected databases: Drop selected databases

Comments

5

As accepted answer kinda demonstrates it, dropping multiple databases was particularly tedious for me, so I wrote an helper script to alleviate this operation : https://github.com/Kraymer/ezdropdb

In short, you enter a pattern that the databases you want to suppress must match then all db names results are listed and there is a final prompt where you can enter which ones of those to drop (cf screenshot on project page) .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.