409

Is there a query (command) to truncate all the tables in a database in one operation? I want to know if I can do this with one single query.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
devang
  • 4,397
  • 7
  • 21
  • 11
  • 2
    Truncate all tables? do you meant truncate all columns of all tables in a database? What query language is this in? (e.g. SQL, MySQL, Oracle, Postgres, etc) – Jay Dec 16 '09 at 07:02
  • thanks 4 the reply but only reason not scripting it is running short of time so thought of runnind a query in mysql – devang Dec 16 '09 at 07:11
  • ya its in mysql..and query means something similar to truncate table table_name..here i want to truncate all rows of all tables in my db in one query – devang Dec 16 '09 at 07:18
  • @Jeffrey Kemp, no one has provided a single query or definitive statement that there is no single query for this. No answer need be accepted. – Ollie Glass Feb 16 '11 at 11:38
  • @Ollie, I find it difficult to accept that *none* of devang's questions have to date been satisfactorily answered. In this case, he even admits that beach's answer was helpful. Anyway, it looks like he's a "fly by" questioner with no interest in improving SO - he hasn't been seen for over 5 months. – Jeffrey Kemp Feb 17 '11 at 02:47
  • Im not sure I would recommend doing this as you could very easily get yourself into trouble. Is there a reason why you cant just script the truncates and run the script? – GrayWizardx Dec 16 '09 at 07:06
  • You can use Information_Schema with a cursor. Not sure about MySql, but it should support Information_Schema.Tables – GrayWizardx Dec 16 '09 at 07:34
  • See also: [How to drop all MySQL tables from the command-line?](http://superuser.com/q/308071/87805). – kenorb Oct 27 '14 at 11:40
  • I have done this in MS SQL server by using T-SQL and storing in procedure. Not sure if similar could be done in MYSql. https://mohitleekha.blogspot.com/2018/07/truncate-microsoft-sql-database-without.html – Mohit Jul 04 '18 at 13:19
  • Here's my case: I want to make hourly backups with the most important data and then daily backups with all the data. The restoration would then look like this: `mysql < last_good_daily_backup.sql` `mysql < last_good_hourly_backup.sql` For this to work as expected, the hourly backup should contain only data, with "TRUNCATE table_name" for all the tables in the hourly backup (but only for them!). – pilat Aug 01 '20 at 08:22

30 Answers30

382

Drop (i.e. remove tables)

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

Truncate (i.e. empty tables)

mysql -Nse 'show tables' DATABASE_NAME | while read table; do mysql -e "truncate table $table" DATABASE_NAME; done
Mathias Bynens
  • 144,855
  • 52
  • 216
  • 248
battousaix
  • 3,853
  • 1
  • 13
  • 2
  • 20
    Yup, clean, ty. But you might need to run this with -uUSER -pPASSWORD. Also you might have to run it multiple times if you have FK withou delete on cascade. – mihaicc Oct 04 '12 at 14:53
  • 51
    If you run into FK problems such as "_Cannot delete or update a parent row: a foreign key constraint fails_", be sure to disable foreign key checks by modifying the command as follows: `mysql -e "SET FOREIGN_KEY_CHECKS = 0; drop table $table" DATABASE_NAME` – chemick Jan 25 '13 at 18:00
  • I've put this in a script with credentials: https://gist.github.com/marcanuy/5977648 – marcanuy Jul 11 '13 at 18:12
  • 28
    No need to loop the mysql client though. Take it out of the loop like this: `mysql -Nse 'show tables' DATABASE_NAME | while read table; do echo "drop table $table;"; done | mysql DATABASE_NAME` – Alexander Shcheblikin Nov 29 '13 at 22:04
  • @mihaicc how did you do it with a password? Don't you need `-uUSER -pPASSWORD` on each `mysql` command, and then it gets weird because it prompts you twice, immediately? It didn't work for me. – Tyler Collier Aug 05 '14 at 16:05
  • 4
    @TylerCollier you need a [.my.cnf](https://rtcamp.com/tutorials/mysql/mycnf-preference/) – Felix Eve Jan 30 '15 at 06:24
  • 1
    Don't know why but this code threw a Syntax Error when applied! – Ifti Mahmud Nov 09 '15 at 08:12
  • 1
    same here I am facing syntax issues – Pramod S. Nikam Jan 13 '16 at 10:19
  • 1
    Due to InnoDB foreign key restrictions and passworded users, I had to slightly modify the answer. This is what worked for me `mysql -u root --password=PASSWORD -Nse 'show tables' DATABASE | while read table; do mysql -u root --password=PASSWORD -e "set_foreign_key_checks=0;truncate table $table" DATABASE;done` – ira Aug 01 '16 at 16:01
  • I am facing syntax issues as well. – nextofsearch Feb 23 '17 at 06:04
  • I figured it out. You should change "set_foreign_key_checks=0" to "set foreign_key_checks=0". Remove the first '_' – nextofsearch Feb 23 '17 at 06:07
  • 3
    Based on the above answer and comments, and because they didn't work as expected for me, i made a simple bash script that you can use for this. You can find it at: https://gist.github.com/mocanuga/eff26a3dcc40ef657a1c812f68511f6d – mocanuga Apr 26 '17 at 11:03
  • @Ahmed To be specific, this command should be used before logging into the MySQL shell. – Madhurya Gandi Aug 20 '18 at 17:32
211

The following query will generate a list of individual truncate commands for all database tables in a Mysql schema(s). (Replace dbSchemaName1 with name of your Db schema.)

SELECT CONCAT('TRUNCATE TABLE ',table_schema,'.',TABLE_NAME, ';') 
    FROM INFORMATION_SCHEMA.TABLES WHERE table_schema IN ('dbSchemaName1','dbSchemaName2');

Copy the query results (which might look like the following) and paste the list of truncate commands into a SQL query tab in MySQL Worbench or your query command tool of choice:

TRUNCATE TABLE dbSchemaName1.table1;
TRUNCATE TABLE dbSchemaName1.table2;
TRUNCATE TABLE dbSchemaName1.table3;

Note: you may receive the following error:

ERROR 1217 (23000): Cannot delete or update a parent row: a foreign key constraint fails

This occurs if there are tables with foreign keys references to the table you are trying to drop/truncate.

To resolve this turn off foreign key checks before running the truncate commands:

SET FOREIGN_KEY_CHECKS=0;  -- turn off foreign key checks
TRUNCATE TABLE dbSchemaName1.table1;  -- truncate tables
TRUNCATE TABLE dbSchemaName1.table2;
TRUNCATE TABLE dbSchemaName1.table3;
SET FOREIGN_KEY_CHECKS=1;  -- turn on foreign key checks
w. Patrick Gale
  • 1,643
  • 13
  • 22
lalit choudhary
  • 2,257
  • 1
  • 12
  • 6
  • 1
    This is probably the best solution if you have a user and password for your database, and you don't want to type them visibly in your shell. – Bach Mar 31 '16 at 10:40
  • 7
    Upvoted because this solution requires only DB access and not SSH access. In addition it's OS-independent. – mastazi Mar 29 '17 at 23:43
  • @mastazi i have a few questions : 1. what is "table_schema"stand for ? is it standing from the schema name? 2.what TABLE_NAME stand for? is it standing for the the tables that should be deleted? 3. should i write tall the tables that should be deleted tin the command like "('db1_name','db2_name')"? – AAEM Aug 17 '18 at 12:17
  • 1
    @Ahmed the only substitutions required is that you have to replace db1_name and db2_name with the names of your databases. Then you have to copy the results of this query, and paste them as a new mysql query and execute them. INFORMATION_SCHEMA is a built-in schema that comes pre-installed in every MySQL installation and holds info about your databases, don't touch it or your MySQL will start misbehaving :-) table_schema and table_name are columns of the table called "TABLES" within information_schema – mastazi Aug 18 '18 at 05:08
  • by "db_name", you mean the name of the schema? i only have 1 schema that i want to delete its tables data – AAEM Aug 18 '18 at 08:55
  • 4
    How do you "use query result" to truncate tables? – The Onin Aug 06 '20 at 18:58
  • The first query will include views, and the `TRUNCATE TABLE` command for them will fail. Should add `table_type = 'BASE TABLE'` to the `WHERE` clause. – reformed Jun 08 '23 at 22:30
82

Use phpMyAdmin in this way:

Database View => Check All (tables) => Empty

If you want to ignore foreign key checks, you can uncheck the box that says:

[ ] Enable foreign key checks

You'll need to be running atleast version 4.5.0 or higher to get this checkbox.

Its not MySQL CLI-fu, but hey, it works!

Nemo
  • 3,104
  • 2
  • 30
  • 46
  • 45
    Who said we didn't? This answer apparently proves useful to people; it helps. – bzeaman Feb 22 '15 at 15:36
  • 3
    This will not work if you have a parent-child database schema. – Cary Bondoc Jan 27 '16 at 01:28
  • 3
    Foreign key constraint fails. – Brian Hannay Jul 27 '17 at 17:30
  • 1
    @BrianHannay Edited the answer to add a note about the checkbox that disables foreign key checks. – Nemo Jul 27 '17 at 17:59
  • @Nemo I used another answer, but for completeness, I wanted to mention that I can't find the foreign key checkbox on PMA Version 4.0.8. – Brian Hannay Jul 27 '17 at 18:51
  • 3
    @BrianHannay It was added in PMA 4.5.0 in June 2015. I found the [changelog](https://github.com/phpmyadmin/history/blob/master/ChangeLogs/ChangeLog-2015#L165) and the [original issue](https://github.com/phpmyadmin/phpmyadmin/issues/6239) – Nemo Jul 27 '17 at 19:08
23

MS SQL Server 2005+ (Remove PRINT for actual execution...)

EXEC sp_MSforeachtable 'PRINT ''TRUNCATE TABLE ?'''

If your database platform supports INFORMATION_SCHEMA views, take the results of the following query and execute them.

SELECT 'TRUNCATE TABLE ' + TABLE_NAME FROM INFORMATION_SCHEMA.TABLES

Try this for MySQL:

SELECT Concat('TRUNCATE TABLE ', TABLE_NAME) FROM INFORMATION_SCHEMA.TABLES

Adding a semicolon to the Concat makes it easier to use e.g. from within mysql workbench.

SELECT Concat('TRUNCATE TABLE ', TABLE_NAME, ';') FROM INFORMATION_SCHEMA.TABLES
beach
  • 8,330
  • 3
  • 29
  • 25
  • hi..thanks for d reply i tried this query but doesnt seem to work..is der something like truncate table table_name which i can use for all tables in my db.. – devang Dec 16 '09 at 07:15
  • I forgot that MySQL doesn't support the "+" operator directly. Assuming that is the error, I added the CONCAT() example above. If you are still getting an error message, then please share the actual error message. – beach Dec 16 '09 at 07:23
  • this query works but what if i have a diff db name eg devang..is my db name so if i use it according to your above query throws the foll error.. Table 'devang.TABLES' doesn't exist – devang Dec 16 '09 at 07:40
  • 3
    Ahh. INFORMATION_SCHEMA is a view that exists in the active database. If you change your database, the view would then be executed against that DB. There is no need to modify the query when changing databases. Just follow these steps: 1) change active database. 2) run the script. 3) copy the results 4) paste the results back into the editor 5) execute the results. All tables in the active database are now truncated. – beach Dec 16 '09 at 07:51
  • Maybe old but still relevant. I still use these techniques today :). I'm glad that you find it useful too. – beach Nov 30 '11 at 07:05
  • This solution will not work, If the tables are having the foreign key constraints. – neni Sep 12 '12 at 06:44
  • None of the solutions will not work without disabling foreign keys first (other than the one that was just added 3 yrs later). Disabling foreign keys is easy - Google for the specific SQL syntax for your DB engine and use the same code above to 1) disable the key check 2) run the truncate commands 3) re-enable the keys. For MySQL, the command appears to be `SET FOREIGN_KEY_CHECKS = 0;` to disable and `SET FOREIGN_KEY_CHECKS = 1;` to enable. For SQL Server, see [link here](http://stackoverflow.com/questions/159038/can-foreign-key-constraints-be-temporarily-disabled-using-t-sql) – beach Sep 22 '12 at 18:35
  • More useful with a where clause: `where information_schema.tables.TABLE_SCHEMA = 'mydb'` – emragins May 04 '14 at 07:19
  • 2
    BEWARE! This selects all tables in all databases (even the ones that are NOT in the current database. The MySQL example doesn't work, but in my case it returned 293 row (tables) instead of 66. Imagine the data loss... – f4der Nov 28 '14 at 12:47
22
SET FOREIGN_KEY_CHECKS = 0;

SELECT @str := CONCAT('TRUNCATE TABLE ', table_schema, '.', table_name, ';')
FROM   information_schema.tables
WHERE  table_type   = 'BASE TABLE'
  AND  table_schema IN ('db1_name','db2_name');

PREPARE stmt FROM @str;

EXECUTE stmt;

DEALLOCATE PREPARE stmt;

SET FOREIGN_KEY_CHECKS = 1;
George Moik
  • 445
  • 4
  • 10
  • 1
    If you want to work with current database (and thus make this code portable), change last condition in `SELECT` to this: `AND table_schema = DATABASE();` – alx Jun 08 '19 at 13:34
  • It doesn't truncate for me. MySQL 5.7.25 – Lucas Bustamante Jun 12 '19 at 16:49
  • Testing on MySQL 5.7.12 (Aurora MySQL 2.7.2), this only truncates the last table from the `SELECT` query. `@str` doesn't seem to concatenate all tables together. – Mike Hill Oct 14 '21 at 20:26
  • I was able to concat all rows with `SELECT @str := GROUP_CONCAT(CONCAT('TRUNCATE TABLE ', table_schema, '.', table_name, '') SEPARATOR ';\n')` – Jairo Feb 07 '22 at 15:34
22

I found this to drop all tables in a database:

mysqldump -uUSERNAME -pPASSWORD --add-drop-table --no-data DATABASENAME | grep ^DROP | mysql -uUSERNAME -pPASSWORD DATABASENAME

Usefull if you are limited by hosting solution (not able to drop a whole database).

I modified it to truncate the tables. There is no "--add-truncate-table" for mysqldump, so i did:

mysqldump -uUSERNAME -pPASSWORD --add-drop-table --no-data DATABASENAME | grep ^DROP | sed -e 's/DROP TABLE IF EXISTS/TRUNCATE TABLE/g' | mysql -uUSERNAME -pPASSWORD DATABASENAME

works for me --edit, fixing a typo in the last command

David Kartik
  • 454
  • 4
  • 9
mbjungle
  • 229
  • 2
  • 3
21

I found it most simple to just do something like the code below, just replace the table names with your own. important make sure the last line is always SET FOREIGN_KEY_CHECKS=1;

SET FOREIGN_KEY_CHECKS=0;
TRUNCATE `table1`;
TRUNCATE `table2`;
TRUNCATE `table3`;
TRUNCATE `table4`;
TRUNCATE `table5`;
TRUNCATE `table6`;
TRUNCATE `table7`;
SET FOREIGN_KEY_CHECKS=1;
Bimal Poudel
  • 1,214
  • 2
  • 18
  • 41
user3357946
  • 327
  • 2
  • 4
  • 7
    you do not have to repeat SET FOREIGN_KEY_CHECKS=0; after every TRUNCATE command just at start line that will mark mode as 0 – HMagdy Jan 12 '15 at 12:24
  • Its not possible to edit and add table name if you table count is higher like more than 500+. – Mithlaj Feb 21 '23 at 07:31
16

This will print the command to truncate all tables:

SELECT GROUP_CONCAT(Concat('TRUNCATE TABLE ',table_schema,'.',TABLE_NAME) SEPARATOR ';') FROM INFORMATION_SCHEMA.TABLES where table_schema in ('my_db');
Gaurav Gupta
  • 5,380
  • 2
  • 29
  • 36
6
  1. To truncate a table, one must drop the foreign key constraints mapped to the columns in this table from other tables (in fact on all tables in the specific DB/Schema).
  2. So, all foreign key constraints must be dropped initially followed by table truncation.
  3. Optionally, use the optimize table (in mysql, innodb engine esp) to reclaim the used data space/size to OS after data truncation.
  4. Once data truncation is carried out, create the same foreign key constraints again on the same table. See below a script that would generate the script to carry out the above operations.

    SELECT CONCAT('ALTER TABLE ',TABLE_SCHEMA,'.',TABLE_NAME,' DROP FOREIGN KEY ',CONSTRAINT_NAME,';') FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
    WHERE CONSTRAINT_TYPE='FOREIGN KEY' AND TABLE_SCHEMA='<TABLE SCHEMA>'
    UNION
    SELECT CONCAT('TRUNCATE TABLE ',TABLE_SCHEMA,'.',TABLE_NAME,';') FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_SCHEMA='<TABLE SCHEMA>' AND TABLE_TYPE='BASE TABLE'
    UNION
    SELECT CONCAT('OPTIMIZE TABLE ',TABLE_SCHEMA,'.',TABLE_NAME,';') FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_SCHEMA='<TABLE SCHEMA>' AND TABLE_TYPE='BASE TABLE'
    UNION
    SELECT CONCAT('ALTER TABLE ',TABLE_SCHEMA,'.',TABLE_NAME,' ADD CONSTRAINT ',CONSTRAINT_NAME,' FOREIGN KEY(',COLUMN_NAME,')',' REFERENCES ',REFERENCED_TABLE_NAME,'(',REFERENCED_COLUMN_NAME,');') FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
    WHERE CONSTRAINT_NAME LIKE 'FK%' AND TABLE_SCHEMA='<TABLE SCHEMA>'
    INTO OUTFILE "C:/DB Truncate.sql" LINES TERMINATED BY '\n';
    

Now, run the Db Truncate.sql script generated

Benefits. 1) Reclaim disk space 2) Not needed to drop and recreate the DB/Schema with the same structure

Drawbacks. 1) FK constraints should be names in the table with the name containing 'FK' in the constraint name.

mbinette
  • 5,094
  • 3
  • 24
  • 32
Anand
  • 61
  • 1
  • 1
4

if using sql server 2005, there is a hidden stored procedure that allows you to execute a command or a set of commands against all tables inside a database. Here is how you would call TRUNCATE TABLE with this stored procedure:

EXEC [sp_MSforeachtable] @command1="TRUNCATE TABLE ?"

Here is a good article that elaborates further.

For MySql, however, you could use mysqldump and specify the --add-drop-tables and --no-data options to drop and create all tables ignoring the data. like this:

mysqldump -u[USERNAME] -p[PASSWORD] --add-drop-table --no-data [DATABASE]

mysqldump usage guide from dev.mysql

Dostee
  • 734
  • 5
  • 12
4

Here is my variant to have 'one statement to truncate 'em all'.

First, I am using a separate database named 'util' for my helper stored procedures. The code of my stored procedure to truncate all tables is:

DROP PROCEDURE IF EXISTS trunctables;
DELIMITER ;;
CREATE  PROCEDURE trunctables(theDb varchar(64))
BEGIN
    declare tname varchar(64);
    declare tcursor CURSOR FOR 
    SELECT table_name FROM information_schema.tables WHERE table_type <> 'VIEW' AND table_schema = theDb;
    SET FOREIGN_KEY_CHECKS = 0; 
    OPEN tcursor;
    l1: LOOP
        FETCH tcursor INTO tname;
        if tname = NULL then leave l1; end if;
        set @sql = CONCAT('truncate `', theDB, '`.`', tname, '`');
        PREPARE stmt from @sql;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
    END LOOP l1;
    CLOSE tcursor;
    SET FOREIGN_KEY_CHECKS = 1; 
END ;;
DELIMITER ;

Once you have this stored procedure in your util database, you can call it like

call util.trunctables('nameofdatabase');

which is now exactly one statement :-)

bebbo
  • 2,830
  • 1
  • 32
  • 37
3

Use this and form the query

SELECT Concat('TRUNCATE TABLE ',table_schema,'.',TABLE_NAME, ';') 
FROM INFORMATION_SCHEMA.TABLES where  table_schema in (db1,db2)
INTO OUTFILE '/path/to/file.sql';

Now use this to use this query

mysql -u username -p </path/to/file.sql

if you get an error like this

ERROR 1701 (42000) at line 3: Cannot truncate a table referenced in a foreign key constraint

the easiest way to go through is at the top of your file add this line

SET FOREIGN_KEY_CHECKS=0;

which says that we don't want to check the foreign key constraints while going through this file.

It will truncate all tables in databases db1 and bd2.

Vinod Kumar
  • 479
  • 5
  • 12
3

here for i know here

   SELECT Concat('TRUNCATE TABLE ',table_schema,'.',TABLE_NAME, ';') 
    FROM INFORMATION_SCHEMA.TABLES where  table_schema in ('databasename1','databasename2');

If cannot delete or update a parent row: a foreign key constraint fails

That happens if there are tables with foreign keys references to the table you are trying to drop/truncate.

Before truncating tables All you need to do is:

SET FOREIGN_KEY_CHECKS=0;

Truncate your tables and change it back to

SET FOREIGN_KEY_CHECKS=1; 

user this php code

    $truncate = mysql_query("SELECT Concat('TRUNCATE TABLE ',table_schema,'.',TABLE_NAME, ';') as tables_query FROM INFORMATION_SCHEMA.TABLES where table_schema in ('databasename')");

    while($truncateRow=mysql_fetch_assoc($truncate)){

        mysql_query($truncateRow['tables_query']);

    }
?>

check detail here link

Jydipsinh Parmar
  • 484
  • 5
  • 14
2

This worked for me. Change database, username and password accordingly.

mysql -Nse 'show tables' -D DATABASE -uUSER -pPWD | while read table; do echo "SET FOREIGN_KEY_CHECKS = 0;drop table \`$table\`;SET FOREIGN_KEY_CHECKS = 1;"; done | mysql DATABASE -uUSER -pPWD
Boken
  • 4,825
  • 10
  • 32
  • 42
Akif
  • 398
  • 9
  • 22
2

No. There is no single command to truncate all mysql tables at once. You will have to create a small script to truncate the tables one by one.

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

Bjørn T.
  • 29
  • 1
2

Ans by battousaix is perfect! I just used his answer and created the final working command for truncate database tables.

mysql -P 3306 -h YOUR_HOST_HERE -u YOUR_USERNAME_HERE -pYOUR_PASSWORD_HERE -Nse 'show tables' DATABASE_NAME | while read table; do mysql -P 3306 -h YOUR_HOST_HERE -u YOUR_USERNAME_HERE -pYOUR_PASSWORD_HERE -e "SET FOREIGN_KEY_CHECKS = 0; truncate table $table" DATABASE_NAME; done

The above command will work perfectly for the MySQL server.

Also, It's included.

SET FOREIGN_KEY_CHECKS = 0

Chandresh M
  • 3,808
  • 1
  • 24
  • 48
1

I find that TRUNCATE TABLE .. has trouble with foreign key constraints, even after a NOCHECK CONSTRAINT ALL, so I use a DELETE FROM statement instead. This does mean that identity seeds are not reset, you could always add a DBCC CHECKIDENT to achieve this.

I Use the code below to print out to the message window the sql for truncating all the tables in the database, before running it. It just makes it a bit harder to make a mistake.

EXEC sp_MSforeachtable 'PRINT ''ALTER TABLE ? NOCHECK CONSTRAINT ALL'''
EXEC sp_MSforeachtable 'print ''DELETE FROM ?'''
EXEC sp_MSforeachtable 'print ''ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all'''
cedd
  • 1,741
  • 1
  • 21
  • 34
1

I know this isn't exactly one command, but the desired result can be achieved from within phpMyAdmin by following these steps:

  1. Select (all) tables to be removed (Check All)
  2. Select "Drop" / "Truncate" from the "With selected:" list
  3. On the confirmation page ("Do you really want to:") copy the query (everything with the red background)
  4. Go at the top and click on SQL and write: "SET FOREIGN_KEY_CHECKS=0;" then paste the previously copied query
  5. Click "Go"

The idea is to quickly get all the tables from the database (which you do in 5 seconds and 2 clicks) but disable foreign key checks first. No CLI and no dropping the database and adding it again.

1

Here is a procedure that should truncate all tables in the local database.

Let me know if it doesn't work and I'll delete this answer.

Untested

CREATE PROCEDURE truncate_all_tables()
BEGIN

   -- Declare local variables
   DECLARE done BOOLEAN DEFAULT 0;
   DECLARE cmd VARCHAR(2000);

   -- Declare the cursor
   DECLARE cmds CURSOR
   FOR
   SELECT CONCAT('TRUNCATE TABLE ', TABLE_NAME) FROM INFORMATION_SCHEMA.TABLES;

   -- Declare continue handler
   DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done=1;

   -- Open the cursor
   OPEN cmds;

   -- Loop through all rows
   REPEAT

      -- Get order number
      FETCH cmds INTO cmd;

      -- Execute the command
      PREPARE stmt FROM cmd;
      EXECUTE stmt;
      DROP PREPARE stmt;

   -- End of loop
   UNTIL done END REPEAT;

   -- Close the cursor
   CLOSE cmds;

END;
beach
  • 8,330
  • 3
  • 29
  • 25
  • Took me a lot of time to figure out why this wasn't working.. Then a comment on this e-mail thread helped: http://forums.mysql.com/read.php?61,116597,219343#msg-219343 - For reference: "Unfortunately, it looks like prepare statements can't be used in cursors. From the manual: http://dev.mysql.com/doc/refman/6.0/en/sql-syntax-prepared-statements.html " – Tominator Feb 25 '14 at 11:19
1

PHP single command:

php -r '$d="PUT_YOUR_DB_NAME_HERE"; $q="show tables"; $dt="drop table"; exec("mysql -Nse \"$q\" $d", $o); foreach($o as $e) `mysql -e "$dt $e" $d`;'

Executed PHP script:

$d="PUT_YOUR_DB_NAME_HERE"; 
$q="show tables"; 
$dt="drop table"; 

exec("mysql -Nse \"$q\" $d", $o); 

foreach($o as $e)
  `mysql -e "$dt $e" $d`;
Grzegorz Adam Kowalski
  • 5,243
  • 3
  • 29
  • 40
1

I find the top answer to be amazing. However it fails when you have an authenticated MySQL Database user.

Here is a solution built on top of the top answer I linked. This solution securely handles authentication without having to:

  • Type the password for each table
  • Worry about your password leaking somewhere
  • Side-effects on other MySQL cnf files (~/.my.cnf) For more details on what these files do, check out resources section at the bottom of this answer.

1. Create local .my.cnf file

vi .temp.my.cnf
[client]
user=<admin_user_goes_here>
password=<admin_password_goes_here>

2. Truncate or drop all tables

2.A Truncate All Tables (empty only)

mysql --defaults-extra-file=.temp.my.cnf -Nse 'show tables' <db_name_goes_here> | while read table; do mysql --defaults-extra-file=.temp.my.cnf -e "truncate table $table" <db_name_goes_here>; done

2.B Drop All Tables (remove entirely)

mysql --defaults-extra-file=.temp.my.cnf -Nse 'show tables' <db_name_goes_here> | while read table; do mysql --defaults-extra-file=.temp.my.cnf -e "drop table $table" <db_name_goes_here>; done

3. Cleanup

Delete your user-password file

rm -rf .temp.my.cnf

Resources:

om-ha
  • 3,102
  • 24
  • 37
0

Soln 1)

mysql> select group_concat('truncate',' ',table_name,';') from information_schema.tables where table_schema="db_name" into outfile '/tmp/a.txt';
mysql> /tmp/a.txt;

Soln 2)

- Export only structure of a db
- drop the database
- import the .sql of structure 

-- edit ----

earlier in solution 1, i had mentioned concat() instead of group_concat() which would have not returned the desired result
Angelin Nadar
  • 8,944
  • 10
  • 43
  • 53
  • 1
    This only seems to return the first table: TRUNCATE table1, and forgets about all the other tables. – Stephen Smith Jul 04 '14 at 18:54
  • 1
    You may get a secure-file-priv error. That is a security feature to allow only a specific directory to be written to. In MySQL type this command: show variables LIKE "secure_file_priv"; It will show you the folder that is able to be written to. In my case it is /var/lib/mysql-files/. Use that instead of /tmp -- just make sure the filename you are writing to is not already in that folder. OR you can disable it in my.cnf in the [mysql] block by putting this line: secure-file-priv='' and restarting MySQL. But if you do that you are turning off a level of security. – Jeff Clayton Jan 05 '22 at 20:28
0

I am not sure but I think there is one command using which you can copy the schema of database into new database, once you have done this you can delete the old database and after this you can again copy the database schema to the old name.

GJ.
  • 4,518
  • 1
  • 19
  • 26
  • 1
    mysqldump -uuser -ppassword --no-data salesLeadsBrittany >salesLeadsTemplate.sql This will create a sql file with the schema only (no data). You can delete the data base after this command and can recreate the database by importing the schema. – GJ. Dec 16 '09 at 07:39
0
TB=$( mysql -Bse "show tables from DATABASE" );
for i in ${TB};
    do echo "Truncating table ${i}";
    mysql -e "set foreign_key_checks=0; set unique_checks=0;truncate table DATABASE.${i}; set foreign_key_checks=1; set unique_checks=1";
    sleep 1;
done

--

David,

Thank you for taking the time to format the code, but this is how it is supposed to be applied.

-Kurt

On a UNIX or Linux box:

Make sure you are in a bash shell. These commands are to be run, from the command line as follows.

Note:

I store my credentials in my ~/.my.cnf file, so I don't need to supply them on the command line.

Note:

cpm is the database name

I am only showing a small sample of the results, from each command.

Find your foreign key constraints:

klarsen@Chaos:~$ mysql -Bse "select concat(table_name, ' depends on ', referenced_table_name)
             from information_schema.referential_constraints
             where constraint_schema = 'cpm'
             order by referenced_table_name"
  1. approval_external_system depends on approval_request
  2. address depends on customer
  3. customer_identification depends on customer
  4. external_id depends on customer
  5. credential depends on customer
  6. email_address depends on customer
  7. approval_request depends on customer
  8. customer_status depends on customer
  9. customer_image depends on customer

List the tables and row counts:

klarsen@Chaos:~$ mysql -Bse "SELECT table_name, table_rows FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'cpm'" | cat -n

 1  address 297
 2  approval_external_system    0
 3  approval_request    0
 4  country 189
 5  credential  468
 6  customer    6776
 7  customer_identification 5631
 8  customer_image  2
 9  customer_status 13639

Truncate your tables:

klarsen@Chaos:~$ TB=$( mysql -Bse "show tables from cpm" ); for i in ${TB}; do echo "Truncating table ${i}"; mysql -e "set foreign_key_checks=0; set unique_checks=0;truncate table cpm.${i}; set foreign_key_checks=1; set unique_checks=1"; sleep 1; done
  1. Truncating table address
  2. Truncating table approval_external_system
  3. Truncating table approval_request
  4. Truncating table country
  5. Truncating table credential
  6. Truncating table customer
  7. Truncating table customer_identification
  8. Truncating table customer_image
  9. Truncating table customer_status

Verify that it worked:

klarsen@Chaos:~$ mysql -Bse "SELECT table_name, table_rows FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'cpm'" | cat -n

 1  address 0
 2  approval_external_system    0
 3  approval_request    0
 4  country 0
 5  credential  0
 6  customer    0
 7  customer_identification 0
 8  customer_image  0
 9  customer_status 0
10  email_address   0

On a Windows box:

NOTE:

cpm is the database name

C:\>for /F "tokens=*" %a IN ('mysql -Bse "show tables" cpm') do mysql -e "set foreign_key_checks=0; set unique_checks=0; truncate table %a; foreign_key_checks=1; set unique_checks=1" cpm
fthiella
  • 48,073
  • 15
  • 90
  • 106
0

The following MySQL query will itself produce a single query that will truncate all tables in a given database. It bypasses FOREIGN keys:

SELECT CONCAT(
         'SET FOREIGN_KEY_CHECKS=0; ',
         GROUP_CONCAT(dropTableSql SEPARATOR '; '), '; ',
         'SET FOREIGN_KEY_CHECKS=1;'
       ) as dropAllTablesSql
FROM   ( SELECT  Concat('TRUNCATE TABLE ', table_schema, '.', TABLE_NAME) AS dropTableSql
         FROM    INFORMATION_SCHEMA.TABLES
         WHERE   table_schema = 'DATABASE_NAME' ) as queries
Roel van Duijnhoven
  • 800
  • 1
  • 7
  • 24
0
mysqldump -u root -p --no-data dbname > schema.sql
mysqldump -u root -p drop dbname
mysqldump -u root -p < schema.sql
emanuele
  • 2,519
  • 8
  • 38
  • 56
0

We can write a bash script like below

truncate_tables_in_mysql() {
    type mysql >/dev/null 2>&1 && echo "MySQL present." || sudo apt-get install -y mysql-client
    
    tables=$(mysql -h 127.0.0.1 -P $MYSQL_PORT -u $MYSQL_USER  -p$MYSQL_PASSWORD -e "USE $BACKEND_DATABASE;    
SHOW TABLES;")
    tables_list=($tables)
    
    query_string="USE $BACKEND_DATABASE; SET FOREIGN_KEY_CHECKS = 0;"
    for table in "${tables_list[@]:1}"
    do
        query_string="$query_string TRUNCATE TABLE \`$table\`; "
    done
    query_string="$query_string SET FOREIGN_KEY_CHECKS = 1;"
    
    mysql -h 127.0.0.1 -P $MYSQL_PORT -u $MYSQL_USER -p$MYSQL_PASSWORD -e "$query_string"
}

You can replace env variables with your MySQL details. Using one command you can truncate all the tables in a DB.

Manisha Bayya
  • 137
  • 1
  • 9
0

Small addition to @Mathias Bynens's answer. When I run this I got an error because foreign key check

mysql -Nse 'SHOW TABLES' <database_name> | while read table; do mysql -e "SET FOREIGN_KEY_CHECKS=0; DROP TABLE $table" <database_name>; done

If there are views in the database it returns an error. I had to clear views manually by drop view <view_name>;

Lakindu Akash
  • 964
  • 1
  • 11
  • 28
-1

An idea could be to just drop and recreate the tables?

EDIT:

@Jonathan Leffler: True

Other Suggestion (or case you dont need to truncate ALL tables):

Why not just create a basic stored procedure to truncate specific tables

CREATE PROCEDURE [dbo].[proc_TruncateTables]
AS
TRUNCATE TABLE Table1
TRUNCATE TABLE Table2
TRUNCATE TABLE Table3
GO
Mark Redman
  • 24,079
  • 20
  • 92
  • 147
  • That loses all constraints, permissions, views, etc on the tables - which is a considerable nuisance. – Jonathan Leffler Dec 16 '09 at 07:29
  • You could do a delete, then reseed all the tables instead of truncate. I assume the mark down is out of frustration. Just restore your backup. – Mark Redman Feb 29 '12 at 19:04
-4
<?php
// connect to database
$conn=mysqli_connect("localhost","user","password","database");

// check connection
if (mysqli_connect_errno()) {
  exit('Connect failed: '. mysqli_connect_error());
}

// sql query
$sql =mysqli_query($conn,"TRUNCATE " . TABLE_NAME);


// Print message
if ($sql === TRUE) {
  echo 'data delete successfully';
}
else {
 echo 'Error: '. $conn->error;
}

$conn->close();

?>

Here is code snippet which I use to clear a table. Just change $conn info and TABLE_NAME.

emmanuel
  • 9,607
  • 10
  • 25
  • 38
  • hey james, i think the OP is looking for firstly a one liner.... and secondly a command to get all tables once off and delete them. this requires some sort of user intervention. thanks for the post though – Craig Wayne May 06 '16 at 06:03