Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop all databases in MySQL

Tags:

We have many databases in our MySQL and we want to shrink/purge ibdata1 file in MySQL.

How can we drop all the databases from the MySQL except information_schema and mysqld databases?

like image 695
Sukhjinder Singh Avatar asked Mar 10 '14 13:03

Sukhjinder Singh


Video Answer


2 Answers

The following command drops all databases in the mysql dbms except mysql, information_schema and performance_schema dbs.

mysql -uroot -p<password> -e "show databases" | grep -v Database | grep -v mysql| grep -v information_schema| gawk '{print "drop database `" $1 "`;select sleep(0.1);"}' | mysql -uroot -p<password>

Thanks to Mohinish's Blog post

like image 165
Sukhjinder Singh Avatar answered Sep 24 '22 15:09

Sukhjinder Singh


You can build a series of DROP DATABASE queries directly using MySQL :

-- Prevent truncation
SET SESSION group_concat_max_len = 1000000;

SELECT GROUP_CONCAT(
  DISTINCT CONCAT('DROP DATABASE ', table_schema, ';')
  SEPARATOR ''
)
FROM information_schema.tables
WHERE table_schema NOT IN ('mysql', 'information_schema');

Then execute the resulting string.

This solution has the virtue of not requiring a connection to the host serving the MySQL database.

like image 21
Fabian Pijcke Avatar answered Sep 22 '22 15:09

Fabian Pijcke