SQL Truncate Table Example
In this article, we are going to explain the SQL Truncate Table through examples.
While using tables in databases, you may need to delete the data of the entire table. In this article, we will study the SQL Truncate Table
command, and use it with an example. We will also understand the difference between the SQL Drop Table
command and the SQL Truncate Table
command.
1. Pre-requisities
If you want to implement the code used in this example, you can do it in two ways.
- Download and install MySQL in your local machine.
- You can use any online SQL compilers.
2. About SQL Truncate Table command
The SQL Truncate Table
the command deletes the data of the table. But, it does not delete the structure of the table. Note that the Truncate Table command is different than the SQL Drop Table command. The SQL Drop Table command deletes both the data
and the structure of the table.
SQL Truncate Table
is same as SQL Delete
command except there is no Where
clause with the former.
3. SQL Truncate Table Syntax
The basic syntax of the SQL Truncate Table
command is given below.
TRUNCATE TABLE tableName;
4. Example
Let us now use the SQL Truncate Table
Command.
- Let us first create a database – demo, and then create a table – example. The example table has two columns – id (of the type
int
), and name (of the typevarchar
).
2. Now, use the SQL Truncate Table
command, and run the SQL Select
Command to find the ‘Empty set’, which means that we have successfully deleted the data of the table.
5. Summary
In this article, we studied the SQL Truncate Table
command. We also explored the command using the example. This article also explained the primary difference between the Drop table command and the Truncate Table command.
6. Download the source code
It is suggested to download the source code and implement it at your own end.
You can download the full source code of this example here: SQL Truncate Table Example