DROP all MySQL tables from the command line

I had a situation today where I wanted to drop all the tables in a database, but didn't have access to a UI like phpMyAdmin. The easiest thing to do would have been to drop the entire database then re-create it, but I didn't have permissions to drop an entire database.

After searching around online, this is the best solution I found:

mysqldump -u username -p --no-data dbname | grep ^DROP > drop.sql
mysql -u username -p dbname < drop.sql
rm drop.txt

Simple, and only requires 2 lines (ok, a 3rd line for cleanup).

What these commands do is basically generated a mysqldump file (which included DROP commands by default), then filter the output to only show the lines that have the DROP statements. The arrow (>) redirects the output to a file. The second line then imports those SQL statements into the database.

The original suggestion I found looked like this:

mysqldump -u username --no-data dbname | grep ^DROP | mysql -u username

The only problem I ran into was I needed to specify a password. When I added the -p password argument, the first mysqldump command got passed an empty password. I could have included the password in the command itself, but that's a security no no.

Tags:

Comments

An other way

You can also generate an sql script from the information_schema database:

Select concat('DROP TABLE database_name.', table_name,';') from information_schema.TABLES where table_schema='database_name';

Which gives:

DROP TABLE database_name.table_name1;
...
DROP TABLE database_name.table-nameN;

You can pipe it to be executed directly (I like to verify first ;-) ) I prefer this syntax than the DROP TABLE IF EXISTS table_name1;

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <strike> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <bash>, <css>, <drupal5>, <drupal6>, <javascript>, <mysql>, <php>, <python>, <ruby>. The supported tag styles are: <foo>, [foo].
  • You can use Markdown syntax to format and style the text. Also see Markdown Extra for tables, footnotes, and more.
  • Web page addresses and e-mail addresses turn into links automatically.

More information about formatting options

Type the characters you see in this picture. (verify using audio)
Type the characters you see in the picture above; if you can't read them, submit the form and a new image will be generated. Not case sensitive.