MySQL Truncate Table

MySQL Truncate Table statement removes all the records or complete data without affecting the table structure or indexes. When you want to remove all the existing records, then the MySQL Truncate Table statement is the best option for you, and its basic syntax is

TRUNCATE TABLE `Schema_Name`.`Table_Name`

We are going to use the following to demonstrate this MySQL Truncate table.

Employee Rows 1

MySQL Truncate Table Example

In this example, we will clear the above-specified.

TRUNCATE TABLE sqltest.empdetails;

Let us see the data in the above table.

SELECT EmpID, `FirstName`, `LastName`,Education, 
       Occupation, YearlyIncome, Sales, HireDate
FROM empdetails;
View Records from the Employees after MySQL Truncate Table Statement

As you can see, it returned 0 records.

Viewing the above MySQL results, you might wonder why we need to Truncate when the Delete Statement without Where Clause can do similarly.

  • Well, it automatically resets the AUTO_INCREMENT counter to the starting point, which is not the possible case for the Delete statement.
  • This statement drops the existing table and recreates the same. Because of this, any Delete triggers won’t fire during this process.

It is another Truncate Table example of using the command prompt or Terminal.

TRUNCATE TABLE sqltest.employeedetails;
MySQL TRUNCATE TABLE Command Prompt Example 4

Using Workbench

If you can access the MySQL Workbench, it is easy to truncate tables. First, select and right-click on the one that you want to clear. Next, select the below-shown option

MySQL Truncate Table Statement 5

It opens a pop-up window. If you want, you can review the query generated by this option by selecting the Review SQL. Otherwise, click the Truncate button.

MySQL Truncate all Tables

In MySQL, you can use the information_schema to get all the tables in a Database. From there, you can remove the required ones.

For instance, the below query returns all the available ones in a database. Therefore, it is instrumental in finding the list of tables available for you. Then perform the required operations on them.

SELECT TABLE_NAME
FROM information_schema.tables
WHERE table_schema = 'sqltest'
List Of Tables 8

Next, you can use this statement to clear one after the other.

TRUNCATE TABLE department

Or, You can use the below code to generate a statement to delete all of them in the database.

SELECT CONCAT('TRUNCATe TABLE ' , TABLE_NAME )
FROM information_schema.tables
WHERE table_schema = 'sqltest'

The above code returns the truncated statement for all of them. You can copy and execute those codes.