Friday, April 30, 2010

Delete and Truncate

Delete and Truncate are both commands in SQL to remove data from a table. But why do we have two commands? Are there any differences? YES! There are differences although the result is same. Both of them delete the data.



Here are few of those differences -

Delete



Truncate



  • 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 de-allocation of the data pages of the table, which makes it faster. Of course, truncate table cannot be rolled back.


  • If you want to keep the identity counter, use delete statement instead.


  • In truncate table the counter used by an identity column for new rows is reset to the seed for the column.


  • On a table referenced by a foreign key constraint, use delete statement without a where clause.


  • You cannot use truncate table on a table referenced by a foreign key constraint.


  • Truncate table is functionally identical to delete statement with no “where clause” both remove all rows in the table. But truncate table is faster and uses fewer system and transaction log resources than delete.


  • Truncate table removes all rows from a table, but the table structure and its columns, constraints, indexes etc., remains as it is. If you want to remove table definition and its data, use the drop table statement.


  • Because truncate table is not logged, it cannot activate a trigger.


  • Truncate table may not be used on tables participating in an indexed view.

1 comment:

Brammadly said...

Just want to say what a great blog you got here!
I've been around for quite a lot of time, but finally decided to show my appreciation of your work!

Thumbs up, and keep it going!

Cheers
Christian, iwspo.net