In this post explains how to use the TRUNCATE TABLE statement in SQL Server (Transact-SQL) with syntax and examples.
The TRUNCATE TABLE statement is used to remove all records from a table in SQL Server. It performs the same function as a DELETE statement without a WHERE clause.
The syntax for the TRUNCATE TABLE statement in SQL Server (Transact-SQL) is:
Optional. If specified, it is the name of the database.
Optional. If specified, it is the name of the schema that the table belongs to.
The table that you wish to truncate.
Optional and can only be used with partitioned tables. If specified, partition_number is the number of the partition that you wish to truncate in the partitioned table. To list multiple partitions, comma separate the partition number values or ranges. If you try to use this clause with a table that is not partitioned, SQL Server will return an error. This feature is not available in all versions of SQL Server.
In SQL Server, truncating a table is a fast way to clear out records from a table if you don't need to worry about rolling back. When a table is truncated, the row deletions are not logged which is why rolling back is not possible. Truncating a table is also a lot easier than dropping the table and recreating it.
Let's look at an example of how to use the TRUNCATE TABLE statement in SQL Server.
For example:
This example would truncate the table called employees and remove all records from that table.
It would be equivalent to the following DELETE statement in SQL Server:
Both of these statements would result in all data from the employees table being deleted. The main difference between the two is that you can roll back the DELETE statement if you choose, but you can't roll back the TRUNCATE TABLE statement.
Let's look at one more example where we prefix the table name with the database name.
For example:
This example would truncate the table called contacts in the database called dbd.
If you want to truncate a specific partition or range of partitions, you can use the WITH PARTITIONS clause.
For example:
In this example, the employees table is a partitioned table and the TRUNCATE TABLE statement would truncate partitions 1 through 5 as well as partition 7 in this partitioned table.
Question: Can you rollback a TRUNCATE TABLE statement in SQL Server?
Answer: A TRUNCATE TABLE statement can be rolled back in SQL Server by using a transaction.
For example:
The SELECT statement above should return the following records:
As you can see, the TRUNCATE TABLE statement was successfully rolled back and the 3 records are still within test_table.