How do I truncate tables properly in MySQL?



This means that you need to first set foreign_key_check to disable and after that you need to truncate tables. The syntax is as follows −

set FOREIGN_KEY_CHECKS = 0;
TRUNCATE TABLE yourTableName1;
TRUNCATE TABLE yourTableName2;
TRUNCATE TABLE yourTableName3;
.
.
.
.
TRUNCATE TABLE yourTableNameN;
set FOREIGN_KEY_CHECKS = 1;

Now, truncate some tables from our database test. The query is as follows −

mysql> set FOREIGN_KEY_CHECKS = 0;
Query OK, 0 rows affected (0.00 sec)

mysql> truncate table skiplasttenrecords;
Query OK, 0 rows affected (0.97 sec)

mysql> truncate table searchtextdemo;
Query OK, 0 rows affected (0.89 sec)

mysql> set FOREIGN_KEY_CHECKS = 1;
Query OK, 0 rows affected (0.00 sec)

To cross check whether the data is present in the table or not −

mysql> select *from searchtextdemo;
Empty set (0.00 sec)

mysql> select *from skiplasttenrecords;
Empty set (0.00 sec)

Empty set tells that there are no record in the table.


Advertisements