Difference Between Delete & Truncate in Sql Server

INTRODUCTION
While working on database, we are using Delete and Truncate without knowing the differences between them and when to use them. In this article we will discuss the difference between Delete and Truncate in Sql.

Delete
  • Delete is a DML command.
  • Delete statement is executed using a row lock,each row in the table is locked for deletion.
  • We can specify filters in where clause.
  • It deletes specified data if where condition exists.
  • Delete activities a trigger because the operation are logged individually.
  • Slower than Truncate because it Keeps logs
Truncate
  • Truncate is a DDL command.
  • Truncate table always lock the table and page but not each row.As it removes all the data.
  • Cannot use Where condition. 
  • It Removes all the data.
  • Truncate table cannot activate a trigger because the operation does not log individual row deletions.
  • Faster in performance wise, because it doesn't keep any logs.
Note
Delete and Truncate both can be rolled back when used with Transaction.
If Transaction is done, means committed then we can not rollback Truncate command from log files, but we can still rollback Delete command from Log files, as delete write records them in Log file in case it is needed to rollback in future from log files.

If you have a Foreign key constraint referring to the table you are trying to truncate, this won't work even if the referring table has no data in it. This is because the foreign key checking is done with DDL rather than DML. This can be got around by temporarily disabling the foreign key constraint(s) to the table.

Delete table is a logged operation. So the deletion of each row gets logged in the transaction log, which makes it slow.
Truncate table also deletes all the rows in a table, but it won't log the deletion of each row instead it logs the deallocation of the data pages of the table, which makes it faster.


~ If accidentally you removed all the data from table using Delete/Truncate. You can rollback committed transaction. Restore the last backup and run transaction log till the time when Delete/Truncate is about to happen.

Check this Article Rollback Table after Truncate Command in Sql or


Let me know if I missed any and I'll add them. 



Comments

Popular posts from this blog

Enable HTTP Transport Security (HSTS) in IIS 7

When to use Truncate and Delete Command in SQL

Extension Class in C#