I've been trying to clean my local databases for some time but I never found the time because it was a slow process. I invested some time searching the fastest way to do this.
You will need command line access to the MySQL server.
The first thing to do is to create a text file with the databases we want to delete. The fastest way I found was to directly dump all the databases and then remove the ones I didn't want to delete. To create a SQL file with all the database names execute this on the terminal:
mysql -u {YOUR-MYSQL-USER} -p{YOUR-MYSQL-PASSWORD} -e "SHOW DATABASES" > deletable-dbs.sql;
You have to replace {YOUR-MYSQL-USER} with your user and {YOUR-MYSQL-PASSWORD} with your password. Note there is no space between -p and the password.
Now we have a deletable-dbs.sql file with the dump of the existing databases. Something like:
Database
information_schema
my_db
antonio
another_db
api_platform
testdb
bubudb
joomla
wordpress
dev
drupal
Now let's format it to remove the databases we want to keep and to add the DROP DATABASE statements. We want a final result like:
DROP DATABASE `my_db`;
DROP DATABASE `antonio`;
DROP DATABASE `another_db`;
DROP DATABASE `api_platform`;
DROP DATABASE `testdb`;
DROP DATABASE `bubudb`;
DROP DATABASE `joomla`;
DROP DATABASE `wordpress`;
DROP DATABASE `dev`;
DROP DATABASE `drupal`;
First remove the initial `Database` line and the databases you want to keep. In this example:
my_db
antonio
another_db
api_platform
testdb
bubudb
joomla
wordpress
dev
drupal
Then using search and replace search for "\n" (a line break) and replace it with "`;\nDROP DATABASE `". The result will be something like:
my_db`;
DROP DATABASE `antonio`;
DROP DATABASE `another_db`;
DROP DATABASE `api_platform`;
DROP DATABASE `testdb`;
DROP DATABASE `bubudb`;
DROP DATABASE `joomla`;
DROP DATABASE `wordpress`;
DROP DATABASE `dev`;
DROP DATABASE `drupal
Then you only have to adjust the first line to add "DROP DATABASE `" before the first db name and add "`;" after the last db name to end with our desired result:
DROP DATABASE `my_db`;
DROP DATABASE `antonio`;
DROP DATABASE `another_db`;
DROP DATABASE `api_platform`;
DROP DATABASE `testdb`;
DROP DATABASE `bubudb`;
DROP DATABASE `joomla`;
DROP DATABASE `wordpress`;
DROP DATABASE `dev`;
DROP DATABASE `drupal`;
Once we have the sql file ready let's save it and execute it with:
mysql -u {YOUR-MYSQL-USER} -p{YOUR-MYSQL-PASSWORD} < deletable-dbs.sql;
If everything went ok you have deleted all the databases!
Do you have a fastest way to do this?