Home >Database >Mysql Tutorial >How Can I Quickly Truncate or Drop All Tables in a MySQL Database Using a Single Command?

How Can I Quickly Truncate or Drop All Tables in a MySQL Database Using a Single Command?

Barbara Streisand
Barbara StreisandOriginal
2024-12-11 09:15:11319browse

How Can I Quickly Truncate or Drop All Tables in a MySQL Database Using a Single Command?

One-Command Solution for Truncating or Dropping All Tables in a MySQL Database

Truncating or dropping tables in a large MySQL database can be a tedious task when performed manually. Fortunately, there are methods to execute this operation with a single command. Let's explore the options available.

Option 1: Dropping Tables

To drop all the tables in a database, use the following command:

mysql -Nse 'show tables' DATABASE_NAME | while read table; do mysql -e "drop table $table" DATABASE_NAME; done

This command executes the following steps:

  1. Uses show tables to list all the tables in the database.
  2. Iterates through each table name using the while loop.
  3. Issues a drop table command for each table to remove it.

Option 2: Truncating Tables

Truncating a table empties it without deleting its structure, unlike dropping it. To truncate all tables in a database, use this command:

mysql -Nse 'show tables' DATABASE_NAME | while read table; do mysql -e "truncate table $table" DATABASE_NAME; done

This command follows the same steps as for dropping tables but uses truncate table instead of drop table to preserve table structures.

The above is the detailed content of How Can I Quickly Truncate or Drop All Tables in a MySQL Database Using a Single Command?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn