9

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?

Hamza Zafeer
  • 2,360
  • 13
  • 30
  • 42
ARMAGEDDON
  • 939
  • 3
  • 11
  • 23

6 Answers6

15

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;
Devart
  • 119,203
  • 23
  • 166
  • 186
4

You can't drop multiple tables in MySQL.

The easiest in your case would be to export the table you want to keep (using a tool like mysqldump), then drop and recreate the database.

Wander Nauta
  • 18,832
  • 1
  • 45
  • 62
  • My table is so large i don't want to export it. It would be then easier to drop each table alone. – ARMAGEDDON Apr 27 '13 at 10:55
  • 1
    Then you should take a look at this question: http://stackoverflow.com/questions/1454328/is-there-a-mysql-command-to-implement-something-like-drop-tables-except-t1-b2 – Wander Nauta Apr 27 '13 at 10:56
1

I wonder why no one suggested to go to the directory :

C:\Program Files (x86)\Parallels\Plesk\Databases\MySQL\data\user_db\...

and delete them easily there? this is what I did and it seems working

Prahalad Gaggar
  • 11,389
  • 16
  • 53
  • 71
ARMAGEDDON
  • 939
  • 3
  • 11
  • 23
  • 1
    It would work, if all the tables would be MyISAM tables. If the database has InnoDB tables, then it wouldn't be that easy... – GregD Apr 27 '13 at 12:48
1

If you have lots of tables, watch out for truncation by the GROUP_CONCAT function. It has a setting for maximum length of the returned string: group_concat_max_len

See: GROUP_CONCAT reference manual entry

This answer guided me to the solution: MYSQL: How to define or get LONG string variables

Community
  • 1
  • 1
G. Stevens
  • 115
  • 3
  • 5
0

You can build all drop statements output them info file and use file after that

SELECT CONCAT( 'DROP TABLE ', table_name , ';' ) AS statement FROM information_schema.tables WHERE table_name not like 'table_to_keep' and table_schema like 'your_schema' into outfile 'path_to_file;
source path_to_file;
alexrider
  • 4,449
  • 1
  • 17
  • 27
0

You can use mysqldump , try it !

mysqldump -u[USERNAME] -p[PASSWORD]--add-drop-table --no-data [DATABASE] |
grep ^DROP |
grep -v 'my_table' |
mysql -u[USERNAME] -p[PASSWORD] [DATABASE]
zey
  • 5,939
  • 14
  • 56
  • 110