devxlogo

The fastest way to delete all the rows in a table

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:

DELETE FROM MyTable

However, in most cases you can speed up your code remarkably with the TRUNCATE TABLE command:

TRUNCATE TABLE MyTable

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.

See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist