How to Drop all Databases from Mysql?

Sometimes I need to clean a mysql server so I can re-import it clean from the backups. A DROP ALL DATABASES; would have been nice, but the following does the trick. It will drop all databases except for mysql, test and information_schema

mysql -uroot -pPASS -e "show databases" | grep -v Database | grep -v mysql| grep -v information_schema| grep -v test | gawk '{print "drop database " $1 ";"}' | mysql -uroot -pPASS

It does what it says on the tin. It will DROP all your databases, no warnings, no confirmations!

The syntax of the DROP DATABASE statement supports only a single database name. You will need to execute a separate DROP DATABASE statement for each database.

You can run a query to return a list of database names, or maybe more helpful, to generate the actual statements you need to run. If you want to drop all databases that start with the literal string database_ (including the underscore character), then:

SELECT CONCAT('DROP DATABASE ',schema_name,' ;') AS stmt
FROM information_schema.schemata
WHERE schema_name LIKE 'database\_%' ESCAPE '\\'
ORDER BY schema_name

Copy the results from that query, and you’ve got yourself a SQL script.

(Save the results as plain text file (e.g. dropdbs.sql), review with your favorite text editor to remove any goofy header and footer lines, make sure the script looks right, save it, and then from the mysql command line tool, mysql> source dropdbs.sql.)

Obviously, you could get more sophisticated than that, but for a one-time shot, this is probably the most efficient.)

How I can change prefixes in all tables in my MySQL DB?


where “test” is expected database name

after this you can long query that will add prefixes if you execute it 😉