Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I drop all empty tables from a MySQL database?

Tags:

mysql

How do I drop all empty tables from a MySQL database, leaving only the tables that have at least 1 record?

EDIT: This is what I did using Python 3 with mysqlclient

import MySQLdb

conn = MySQLdb.connect(
    host='localhost', user='root',
    passwd='mypassword', db='mydatabase'
)

c = conn.cursor()
c.execute('SHOW TABLES')
for row in c.fetchall():
    table_name = row[0]
    c.execute(f'SELECT * FROM {table_name}')
    if c.rowcount == 0:
        # c.execute(f'DROP TABLE {table_name}')
        print(f'DROP TABLE {table_name}')
like image 991
fmalina Avatar asked Oct 18 '09 12:10

fmalina


2 Answers

Use pt-find from Percona Toolkit:

$ pt-find --dblike "mydatabase" --empty --exec-plus "DROP TABLE %s"
like image 74
Bill Karwin Avatar answered Nov 12 '22 10:11

Bill Karwin


This stored procedure should do it:

DELIMITER $$

DROP PROCEDURE IF EXISTS `drop_empty_tables_from` $$

CREATE PROCEDURE `drop_empty_tables_from`(IN schema_target VARCHAR(128))
BEGIN
    DECLARE table_list TEXT;
    DECLARE total      VARCHAR(11);

    SELECT
        GROUP_CONCAT(`TABLE_NAME`),
        COUNT(`TABLE_NAME`)
    INTO
        table_list,
        total
    FROM `information_schema`.`TABLES`
    WHERE
          `TABLE_SCHEMA` = schema_target
      AND `TABLE_ROWS`   = 0;

    IF table_list IS NOT NULL THEN
        SET @drop_tables = CONCAT("DROP TABLE ", table_list);

        PREPARE stmt FROM @drop_tables;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
    END IF;

    SELECT total AS affected_tables;
END $$

DELIMITER ;

There may be problems with that GROUP_CONCAT when there are too many empty tables. It depends on the value of the group_concat_max_len system variable.

It's not possible to do it in one query because DROP TABLE cannot receive its arguments from a SELECT query.

InnoDB note

Thanks to James for his comments. It appears that the row count query won't return precise results in the case of InnoDB tables, so the above procedure is not guaranteed to work perfectly when there are InnoDB tables in that schema.

For InnoDB tables, the row count is only a rough estimate used in SQL optimization. (This is also true if the InnoDB table is partitioned.)

Source: http://dev.mysql.com/doc/refman/5.1/en/tables-table.html

like image 4
Ionuț G. Stan Avatar answered Nov 12 '22 12:11

Ionuț G. Stan