MySQL Empty Database / Delete or Drop All Tables

Posted on in Categories , , , , , , , , , , , last updated November 13, 2008

Q. How do I empty MySQL database? What SQL command needs to be executed in order to delete all (100s) of tables in MySQL database called atomstore?

A. You need to use DROP DATABASE sql command to drops all tables in the database/empty database and deletes the database. Be very careful with this statement! To use DROP DATABASE, you need the DROP privilege on the database

MySQL drop all tables syntax:

DROP DATABASE {mysql-database-name}

Method #1: Empty database with root user

In order to use this procedure you must have the drop and create database privilege (otherwise you will drop database but not able to create it again). Login as MySQL root or admin user to drop atomstore database:
$ mysql -u root -p
Now drop database:
mysql> DROP DATABASE atomstore;
Now create database again:
mysql> CREATE DATABASE atomstore;
Exit and close the session:
mysql> quit

Method #2: Drop all tables using shell script w/o root access

I’ve small handy shell script that removes all tables without dropping and creating MySQL database again.

#!/bin/bash
MUSER="$1"
MPASS="$2"
MDB="$3"
 
# Detect paths
MYSQL=$(which mysql)
AWK=$(which awk)
GREP=$(which grep)
 
if [ $# -ne 3 ]
then
	echo "Usage: $0 {MySQL-User-Name} {MySQL-User-Password} {MySQL-Database-Name}"
	echo "Drops all tables from a MySQL"
	exit 1
fi
 
TABLES=$($MYSQL -u $MUSER -p$MPASS $MDB -e 'show tables' | $AWK '{ print $1}' | $GREP -v '^Tables' )
 
for t in $TABLES
do
	echo "Deleting $t table from $MDB database..."
	$MYSQL -u $MUSER -p$MPASS $MDB -e "drop table $t"
done

Simply use above script as follows to empty a database called quiz with username tom and password jerry:
$ ./drop.table.sh tom jerry quiz

Download MySQL empty database drop script

You can download complete script with error checking below:

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

49 comment

  1. Alternative methods:

    In PHPMyAdmin, you can check all tables and then choose with selected: drop.

    If you are doing it with scripting, You can use SHOW TABLES to list the tables, and use this to generate a query DROP TABLE [tablename],[tablename]…

  2. You can have the drop privilege, but not the create database one!!

    BE CAREFUL WHEN DOING THIS! You might end up with no DB at all.

    Please don’t suggest this kind of procedures without explaining the whole nine yards.

  3. Unfortunately this is no use if you don’t have permissions for create database (like the situation i am currently in).

  4. Great post and you do not need create database privileges for this. The method is only dropping the tables and not the database. The user should have create tables under the database..

    Thanks

  5. What about :
    mysqldump -u[user] -p[ssht...] --add-drop-table --no-data [DATABASE] | grep ^DROP | mysql -u[user] -p[sshht...] [DATABASE]

  6. A little longer, but also a little more efficient because it does the drop (of all tables) in one shot:


    mysql --user=YOUR_USERNAME --password=YOUR_PASSWORD -BNe "show tables" YOUR_DBSCHEMA_NAME | tr '\n' ',' | sed -e 's/,$//' | awk '{print "SET FOREIGN_KEY_CHECKS = 0;DROP TABLE IF EXISTS " $1 ";SET FOREIGN_KEY_CHECKS = 1;"}' | mysql --user=YOUR_USERNAME --password=YOUR_PASSWORD YOUR_DBSCHEMA_NAME

    1. When the database contains tables with names that are the same as the MySQL reserved keywords (for instance ‘right`), you need a minor addition:

      mysql --user=YOUR_USERNAME --password=YOUR_PASSWORD -BNe "show tables" YOUR_DBSCHEMA_NAME | tr '\n' ','  | sed -e 's/,/`,`/g' | sed -e 's/,`$//' | sed -e 's/^/`/' | awk '{print "SET FOREIGN_KEY_CHECKS = 0;DROP TABLE IF EXISTS " $1 ";SET FOREIGN_KEY_CHECKS = 1;"}' | mysql --user=YOUR_USERNAME --password=YOUR_PASSWORD YOUR_DBSCHEMA_NAME
      

      This adds back-ticks around the table names

  7. I agree with Romina

    I followed it and ended with completely deleting the database and not just the tables!! Your post title is absolutely incorrect. Please change it..

    EVERYONE BE CAREFUL WHILE DOING THIS

  8. I want to erase everything that has been looked up on google and everything that has already been looked up like a restart how can i reboot?

  9. I like this even more.

    echo “select concat(‘drop table ‘, table_name, ‘;’) from information_schema.tables where table_schema=schema()” | mysql CONNECT | grep “^drop table ” | mysql CONNECT

    Make sure you connect to the right schema :p

  10. To empty the database in MySql just go to the database and select the all tables (checkbox on of all tables) then select the “empty” action just down from the table names, then click “GO” button just right side of action selected .

  11. Call me paranoid, but I don’t like to put my database password in scripts. So I replaced the definition of MPASS with

    read -s -p "Your database password: " MPASS
    
  12. Had to put the table name in quotes in the for loop:

    $MYSQL -u $MUSER -p$MPASS $MDB -e “drop table \`$t\`”

  13. I use the script all the time to save me from needing to add privileges again if I’m clearing out a db. Thanks a lot.

  14. little mod for remote hosts:

    #!/bin/bash
    MUSER="$1"
    MPASS="$2"
    MDB="$3"
    HOST="$4"
     
    # Detect paths
    MYSQL=$(which mysql)
    AWK=$(which awk)
    GREP=$(which grep)
     
    if [ $# -ne 4 ]
    then
    	echo "Usage: $0 {MySQL-User-Name} {MySQL-User-Password} {MySQL-Database-Name} {MySQL-Database-Host}"
    	echo "Drops all tables from a MySQL"
    	exit 1
    fi
     
    TABLES=$($MYSQL -h $HOST -u $MUSER -p$MPASS $MDB -e 'show tables' | $AWK '{ print $1}' | $GREP -v '^Tables' )
     
    for t in $TABLES
    do
    	echo "Deleting $t table from $MDB database..."
    	$MYSQL -h $HOST -u $MUSER -p$MPASS $MDB -e "drop table $t"
    done
    
  15. Combined Lon F. Binder, Sutharsan, and Andrea De Pirro’s suggestions into one script, using getopt to make the DB host and port optional:

    #!/bin/bash
    
    usage()
    {
    cat <<EOF
    usage: $0 options
    
    WARNING! This script will drop all tables from a MySQL database
    
    OPTIONS:
       -u      Database username
       -d      Database/schema name
       -h      Host name (optional)
       -p      Port (optional)
    EOF
    }
    
    USERNAME=
    DBSCHEMA=
    HOST=
    PORT=
    
    # Read options from command line
    while getopts “u:d:h:p” OPTION
    do
         case $OPTION in
    	 u)
    	     USERNAME=$OPTARG
                 ;;
    	 d)
    	     DBSCHEMA=$OPTARG
                 ;;
             h)
    	     HOST=$OPTARG
                 ;;
             p)
                 PORT=$OPTARG
                 ;;
             ?)
                 usage
                 exit
                 ;;
         esac
    done
    
    # Make sure all required options are supplied
    if [[ -z $USERNAME ]] || [[ -z $DBSCHEMA ]] 
    then
         usage
         exit 1
    fi
     
    # Read password from stdin
    read -s -p "Your database password: " PASSWORD
    
    # Construct MySQL command line options
    MYSQL_OPTS="--user=$USERNAME --password=$PASSWORD"
    if [[ ! -z $HOST ]]
    then
        MYSQL_OPTS="$MYSQL_OPTS --host=$HOST"
    fi 
    if [[ ! -z $PORT ]]
    then
        MYSQL_OPTS="$MYSQL_OPTS --port=$PORT"
    fi 
    
    # Get the table names
    TABLES=$(mysql $MYSQL_OPTS -BNe "show tables" $DBSCHEMA | tr '\n' ',' | sed -e 's/,$//' | awk '{print "SET FOREIGN_KEY_CHECKS = 0;DROP TABLE IF EXISTS " $1 ";SET FOREIGN_KEY_CHECKS = 1;"}')
    
    # Actually drop the tables
    mysql $MYSQL_OPTS -BNe "$TABLES" $DBSCHEMA
    
  16. The script method worked like a charm on cento6.

    In case the
    ———————-
    $ ./drop.table.sh tom jerry quiz
    ———————–
    doesnt work, since don’t have root access, you can also do it with the simple sh command.

    ———————-
    [[email protected]] sh drop.table.sh tom jerry quiz [enter]
    ———————-

  17. JUST BE CAREFUL!

    I just wanted to delete my records from the tables not the tables itself and stored procedures! But I have deleted the whole database with this command.
    Is there any way to recover ?

  18. SET FOREIGN_KEY_CHECKS=0;
    SET @tables = NULL;
    SELECT GROUP_CONCAT(table_schema, '.', table_name) INTO @tables
      FROM information_schema.tables 
      WHERE table_schema = 'database-name-here'; -- specify DB name here.
    
    SET @tables = CONCAT('DROP TABLE ', @tables);
    PREPARE stmt FROM @tables;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    SET FOREIGN_KEY_CHECKS=1;

    Source here

  19. I have an old Staff Attendance Program. There is a Master Program and all connected to msyql database. When I tried to open the Staff Attendance Program a message box pops up…”This program was last run on 12-Feb-2029. Current server date is 20-Mar-2014. Admin should change the server date.” When I opened the mysql tables to check, I can see a calendar table for year 2029. How to go about solving the problem please?
    I am the headmaster of the school and I dont have any technical knowledge. Help please.
    Thanks.
    patricklee

  20. Worked perfectly. I made a few tweaks — added the hostname and put the password as the last argument. The modified one is below in case it is interesting to someone…

    #!/bin/bash                                                                                                                                                                                            
    HOST="$1"
    MUSER="$2"
    MDB="$3"  
    MPASS="$4"
    
    # Detect paths                                                                                                                                                                                         
    MYSQL=$(which mysql)
    AWK=$(which awk)
    GREP=$(which grep)
    
    if [ $# -ne 4 ]
    then
        echo "Usage: $0 {MySQL-Host-Name} {MySQL-User-Name} {MySQL-Database-Name} {MySQL-User-Password}"
        echo "Drops all tables from a MySQL"
        exit 1
    fi
    
    TABLES=$($MYSQL -h $HOST -u $MUSER -p$MPASS $MDB -e 'show tables' | $AWK '{ print $1}' | $GREP -v '^Tables' )
    
    for t in $TABLES
    do
        echo "Deleting $t table from $MDB database..."
        $MYSQL -h $HOST -u $MUSER -p$MPASS $MDB -e "drop table $t"
    done
    
  21. If you want to force delete the tables even if they are any foreign key relation exists , just update the line

    $MYSQL -u $MUSER -p$MPASS $MDB -e “drop table $t”
    to

    $MYSQL -u $MUSER -p$MPASS $MDB -e “SET FOREIGN_KEY_CHECKS = 0;drop table $t”

  22. In case you don’t want to post your database password in clear text in the terminal (also added requirement for host designation:

    #!/bin/bash
    MUSER="$1"
    MDB="$2"
    MDBS="$3"
    
    # Detect paths
    MYSQL=$(which mysql)
    AWK=$(which awk)
    GREP=$(which grep)
    
    if [ $# -ne 3 ]
    then
            echo "Usage: $0 {MySQL-User-Name} {MySQL-Database-Name} {MySQL-Database-Server}"
            echo "Drops all tables from a MySQL"
            exit 1
    fi
    
    echo -e "Please enter MySQL password for $MUSER"
    read -s MPASS
    
    TABLES=$($MYSQL -u $MUSER -p$MPASS -D $MDB -h $MDBS -e 'show tables' | $AWK '{ print $1}' | $GREP -v '^Tables' )
    
    for t in $TABLES
    do
            echo "Deleting $t table from $MDB database..."
            $MYSQL -u $MUSER -p$MPASS -D $MDB -h $MDBS -e "drop table $t"
    done
    

Comments are closed.