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.

Share the Post:
Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several