Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: SS7
Expertise: beginner
Sep 9, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

The fastest way to delete all the rows in a table

The standard way to delete all the rows in a SQL Server table is a DELETE statement without a WHERE clause:
However, in most cases you can speed up your code remarkably with the TRUNCATE TABLE command:
This statement is faster, because it doesn't delete rows one by one; instead, it directly deallocates all the data pages allocated to the table. As with the DELETE statement, TRUNCATE TABLE raises an error if the operation violates the referential integrity rules of the database, and the operation is fully logged, so you can rollback it if it's inside a transaction.

There are two major differences from DELETE that you should keep into account: TRUNCATE TABLE resets the IDENTITY counters and doesn't fire any trigger, if there is one. Keep these differences into account if you replace your DELETE statements with TRUNCATE TABLE. UPDATE: There is also another major difference between DELETE and TRUNCATE TABLE: TRUNCATE TABLE permissions default to the table owner and are not transferable. Also, this permission is typically not granted by a DBA to user accounts. Thanks to Michael D.Long for this clarification. UPDATE: Martin Lanza send us an interesting note on using TRUNCATE. The statistics are not reset, various items in sysindexes are not updated, etc. Under SS65 Martin encountered problems with tables truncated and as a general rule he now always issue a DBCC CHECKTABLE command to fix the problem.

Francesco Balena
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date