Sunday, November 25, 2012

SQL Truncate vs. Delete

By now as you know, in this post I am going to discuss about two SQL commands we use regularly to clear data in our tables.

Usage





  1. DELETE FROM TABLENAME
  2. TRUNCATE TABLE TABLENAME




Even though they do a similar thing, there are some differences which makes them unique commands.

 

DELETE

TRUNCATE

1. Considered as Data Mining Language (DML) statement. Considered as Data Definition Language (DDL) statement.
2. Can be used to delete all or part of data in a table. Will delete all the data in a table.
3. Will log the actions. There will be no logging on record deletion.
4. Will use more locks. Will use fewer locks.
5. Will use more resources. Will use less resources.
6. Slow. Fast.
7. Will not reset the identity seed. Will reset the identity seed to 0.
8. Can be used to delete data in tables having relationships. Cannot use in tables having relationships.
9. Can be used in tables involved in log shipping or replication. Cannot be used in tables involved in log shipping or replication.
10. Transaction can be rolled back. No rollback.
11. Table may keep the empty pages. Can be released by running, SHRINKDATABASE (Database Name). Data pages related to the table will be de allocated and returned to the system.
12. Related Triggers are fired. Triggers are not fired.

 

If you used DELETE to fully remove all the records, you can reset the identity value by running the following command.





  1. DBCC CHECKIDENT (TABLENAME, RESEED, 0)




If you do have some rows left in table, simply replace 0 with the last identity column value. For example if you put 5 instead of 0 then the next record inserted into the table will have an identity column value of 6.

If you jus need to check the current identity value just use the following command.





  1. DBCC CHECKIDENT (TABLENAME, NORESEED)




No comments: