When it comes to deleting data from a table, there are two main commands that can be used: DELETE and TRUNCATE. While both of these commands can be used to remove data from a table, they have some key differences that should be taken into consideration. In this article, we'll explore the differences between DELETE and TRUNCATE, as well as when each command should be used. The DELETE statement is used to delete one or more records from an existing table based on the specified condition.
This command is part of the Data Manipulation Language (DML) and allows for more control over which records are deleted. The DELETE command also preserves the statistics of the object and the allocated space, as well as any delete triggers that may be defined in the table. The TRUNCATE command, on the other hand, removes complete data from an existing table, but not the table itself. This command is part of the Data Definition Language (DDL) and can be used to quickly remove all data from a table without maintaining the integrity of the table.
Unlike DELETE, TRUNCATE unmaps all pages of data in a table and removes all statistics and allocated space. It's important to note that TRUNCATE should never be used if delete triggers are defined in the table to perform some automatic cleaning or logging action when deleting rows. Additionally, TRUNCATE cannot be used if another user or role has been granted deletion in a table without using a DROP ANY TABLE grant. At a higher level, you might consider truncating a command similar to a DELETE statement without a WHERE clause.
Rows removed by the TRUNCATE TABLE statement cannot be restored and the WHERE clause cannot be specified in the TRUNCATE statement. Finally, it's worth noting that while most sites and even Microsoft say that Truncate can't be undone, it can actually be undone if you start with the transaction like with a DELETE statement. In conclusion, there are many ways to delete data in SQL, including the DELETE, TRUNCATE TABLE, and DROP TABLE commands. However, it's important to understand the differences between DELETE and TRUNCATE before using either command.
The DELETE statement can have a WHERE clause to delete specific records, whereas the TRUNCATE statement requires none and deletes the entire table. Additionally, delete triggers are not executed when using TRUNCATE.