Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop All Tables Except One in MySql

Tags:

mysql

I have 100 tables in my database, I want to keep one only.

I tried something like below query:

DROP ALL TABLES EXCEPT my_table

But that doesn't seem to exist. any idea?

like image 787
ARMAGEDDON Avatar asked Apr 27 '13 10:04

ARMAGEDDON


1 Answers

You can build a DROP TABLE statement with multiple listed tables, and run the query using MySQL prepared statements -

SET @tables = NULL;
SELECT GROUP_CONCAT(table_schema, '.', table_name) INTO @tables FROM information_schema.tables 
  WHERE table_schema = 'Database1' AND table_name <> 'my_table';

SET @tables = CONCAT('DROP TABLE ', @tables);
PREPARE stmt1 FROM @tables;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
like image 106
Devart Avatar answered Oct 13 '22 21:10

Devart