This tutorial highlights how to use MySQL TRUNCATE statements to remove all the data in a database table.
MySQL TRUNCATE statement is part of the Data Definition Language statements. However, its functions are similar to the DELETE statement, making it seem a part of Data Manipulation Language.
To use the TRUNCATE statement, you must have the DROP privileges on the database.
Features of Truncate
The following are some of the salient features of the TRUNCATE statement that makes it different from the DELETE statement:
- A truncate operation cannot be rolled back as it performs an implicit commit.
- It works by deleting the table and re-creating it, preserving its structure but not the data.
- Truncate supports corrupt tables, removing all the data and restoring an empty table.
- It does not invoke any delete triggers.
- It preserves a table’s partitioning
- The TRUNCATE statement does not return any information regarding the affected rows—meaning that the return value is 0.
The general syntax for using the TRUNCATE statement is:
NOTE: You can skip the TABLE keyword, and the TRUNCATE statement will perform similarly. However, it is better to add the TABLE keyword to avoid confusion with the Truncate function.
Example Use Case
Let’s look at an example of how to use the TRUNCATE statement.
For this example, I will use the employees’ table provided in the resource below:
First, select a few values from the table to confirm it is not empty:
The output is shown below:
Now that we have confirmed that the table is full of data, let us try to truncate the table as:
We first set the FOREIGN_KEY_CHECK variable to False because the TRUNCATE statement fails if the table contains constraints from other tables.
Once we have removed the ability to check constraints from other tables, we call the TRUNCATE statement to remove the data.
You can confirm by clicking select:
CAUTION: Do not remove the check for constraints in tables in a real-world database.
This guide walked you through how to use the TRUNCATE statement in MySQL to remove data in a table. I hope the tutorial was helpful.