13

I have a development database (MYSQL) which I would like to load with fresh data at some point. I would like to delete the content of all tables. What is the best way, as automated as possible, to delete the content of all tables (including those that have foreign key constraints). Is there a truncate all/ drop all equivalent constraints?

Thanks

rubdottocom
  • 8,110
  • 10
  • 39
  • 59

4 Answers4

29

I think you can do the following:

  1. Disable the foreign key constraint check

    mysql> SET FOREIGN_KEY_CHECKS = 0;
    
  2. Truncate your tables

    mysql> TRUNCATE MY_TABLE;
    
  3. Enable the foreign key constraint check

    mysql> SET FOREIGN_KEY_CHECKS = 1;
    

I prefer disabling the foreign key constraints temporarily to dropping/recreating them.

Pascal Thivent
  • 562,542
  • 136
  • 1,062
  • 1,124
  • Quick comment for anyone using `PHPMYADMIN` to do this. If you perform all of the above statements in one SQL line, it works. If you try to do it one at a time, it doesn't work. Of course, I am sure it works on the regular `mysql` command line as @Pascal Thivent shows. – Sablefoste Mar 11 '13 at 21:40
0

If you want truncate REALLY all tables better way i'm think drop and create database with previously extracted database schema. Or you just can two copy of same database - test and empty. After filling your tables, just delete test db and copy empty to test.

Alexey Sviridov
  • 3,360
  • 28
  • 33
0

TRUNCATE (TABLE) tbl_name will truncate a single table. You can stick that in a script and loop through it with all of your table names.

http://dev.mysql.com/doc/refman/5.0/en/truncate.html

You may want to look into migrations, too, but I think Alexey has the right approach there. It's very similar to how RoR handles rebuilding the test database on each run.

user179161
  • 61
  • 1
  • 1
0

Here's what I do from the command prompt:

 mysql -Nse 'show tables' DATABASE_NAME | while read table; do mysql -e "SET FOREIGN_KEY_CHECKS = 0; TRUNCATE table $table" DATABASE_NAME; done

Problem is, if you require authentication, you will need to add a -u YOUR_USERNAME -pYOURPASSWORD after both mysql commands.

If you don't want to enter your password at the command prompt (I don't ever), then you'll need to copy and paste the password after every prompt, which may be several times depending on the number of tables.

Berto
  • 702
  • 2
  • 9
  • 19