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.
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.
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
psql -d postgres < <( psql -Atc "select 'drop database \"'||datname||'\";' from pg_database where datistemplate=false /* AND add_extra_conditions_here */;")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) .