Alex Rivera | Logout

SQL: deleting tables with prefix

Asked 2009-10-19T15:14:44.300
123

How to delete my tables who all have the prefix myprefix_?

Note: need to execute it in phpMyAdmin

Edit
Report

2 Answers

48

Some of the earlier answers were very good. I have pulled together their ideas with some notions from other answers on the web.

I needed to delete all tables starting with 'temp_' After a few iterations I came up with this block of code:

-- Set up variable to delete ALL tables starting with 'temp_'
SET GROUP_CONCAT_MAX_LEN=10000;
SET @tbls = (SELECT GROUP_CONCAT(TABLE_NAME)
               FROM information_schema.TABLES
              WHERE TABLE_SCHEMA = 'my_database'
                AND TABLE_NAME LIKE 'temp_%');
SET @delStmt = CONCAT('DROP TABLE ',  @tbls);
-- SELECT @delStmt;
PREPARE stmt FROM @delStmt;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

I hope this is useful to other MySQL/PHP programmers.

answered 2013-06-26T21:29:24.887
6
SELECT CONCAT("DROP TABLE ", table_name, ";") 
FROM information_schema.tables
WHERE table_schema = "DATABASE_NAME" 
AND table_name LIKE "PREFIX_TABLE_NAME%";
answered 2013-05-31T11:45:10.697

Your Answer