TRUNCATE vs DELETE in sql

 In SQL Server, the TRUNCATE command is generally faster than the DELETE command for a few reasons:

  1. Locking and Logging: DELETE operates on a row-by-row basis and logs each row deletion in the transaction log, which can be resource-intensive. On the other hand, TRUNCATE operates at the page level, deallocating data pages and removing index pointers. This requires fewer locks and less logging, making it faster.

  2. No WHERE clause: DELETE can remove specific rows based on a WHERE clause, which requires processing time to evaluate each rowTRUNCATE removes all rows from a table without needing to evaluate any conditions.

  3. Space Reclamation: TRUNCATE reclaims the space used by the table for immediate use by the system DELETE does not reclaim space immediately.

  4. Resetting Identity Values: TRUNCATE resets the identity of the table. If the table has an identity column, TRUNCATE will reset the identity value to the seed for the column. In contrast, DELETE does not reset the identity value.

  5. Transaction Space: TRUNCATE uses less transaction space than DELETE.

However, it’s important to note that TRUNCATE cannot be used if the table is referenced by a Foreign Key or if you want to delete specific rows. Always consider the requirements of your operation before choosing between TRUNCATE and DELETE.


You can rollback TRUNCATE and DELETE operations in SQL Server, but there are some conditions:

  • Transactions: Any operation, including TRUNCATE and DELETE, can be rolled back if it is performed within a transaction and the transaction is not yet committed. If the session is closed, a TRUNCATE operation cannot be rolled back, but a DELETE operation can.

  • TRUNCATE Specifics: TRUNCATE is a logged operation, but SQL Server doesn’t log every single row as it truncates the table. SQL Server only logs the fact that the TRUNCATE operation happened. It also logs the information about the pages and extents that were deallocated. However, there’s enough information to roll back, by just re-allocating those pages.

Here’s an example of how you can use transactions to rollback a TRUNCATE operation:

BEGIN TRANSACTION
TRUNCATE TABLE YourTable;
ROLLBACK

In this example, the TRUNCATE operation will be rolled back, and the data in YourTable will not be affected.

However, it’s important to note that if a TRUNCATE or DELETE operation is performed outside of a transaction, or if the transaction in which they are performed is committed, then you cannot roll back the operation using the ROLLBACK command. In such cases, you would have to restore from backups or use other data recovery methods.

Vikash Chauhan

C# & .NET experienced Software Engineer with a demonstrated history of working in the computer software industry.

Post a Comment

Previous Post Next Post

Contact Form