Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I drop all MySQL Databases with a certain prefix?

Tags:

shell

mysql

I need to drop hundreds of mysql databases that all share a common prefix, but have random id's as the rest of their name ( eg. database_0123456789, database_9876543210 ). All these databases are on the same server. There are other databases on that same server that I don't want to drop.

This is what I'd like to do:

DROP DATABASE `database_*`;

How can I drop these efficiently? Is there a MySQL query I can run? Maybe a shell script?

like image 513
T. Brian Jones Avatar asked Aug 16 '13 18:08

T. Brian Jones


2 Answers

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.)

like image 122
spencer7593 Avatar answered Sep 22 '22 16:09

spencer7593


Don't need of an external script file. A stored procedure using prepare statements might do the trick:

CREATE PROCEDURE kill_em_all()
BEGIN
    DECLARE done INT DEFAULT FALSE;
    DECLARE dbname VARCHAR(255);
    DECLARE cur CURSOR FOR SELECT schema_name
      FROM information_schema.schemata
     WHERE schema_name LIKE 'database\_%' ESCAPE '\\'
     ORDER BY schema_name;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

    OPEN cur;

    read_loop: LOOP
        FETCH cur INTO dbname;

        IF done THEN
          LEAVE read_loop;
        END IF;

        SET @query = CONCAT('DROP DATABASE ',dbname);
        PREPARE stmt FROM @query;
        EXECUTE stmt;
    END LOOP;
END;

Once you have that procedure, you just have to:

CALL kill_em_all();

When done:

DROP PROCEDURE kill_em_all
like image 5
Sylvain Leroux Avatar answered Sep 23 '22 16:09

Sylvain Leroux