Deleting All Rows by Using TRUNCATE TABLE

The TRUNCATE TABLE statement is a fast, efficient method of deleting all rows in a table. TRUNCATE TABLE is similar to the DELETE statement without a WHERE clause. However, TRUNCATE TABLE is faster and uses fewer system and transaction log resources.

Compared to the DELETE statement, TRUNCATE TABLE has the following advantages:

  • Less transaction log space is used.

    The DELETE statement removes rows one at a time and records an entry in the transaction log for each deleted row. TRUNCATE TABLE removes the data by deallocating the data pages used to store the table data and records only the page deallocations in the transaction log.

  • Fewer locks are typically used.

    When the DELETE statement is executed using a row lock, each row in the table is locked for deletion. TRUNCATE TABLE always locks the table and page but not each row.

  • Without exception, zero pages are left in the table.

    After a DELETE statement is executed, the table can still contain empty pages. For example, empty pages in a heap cannot be deallocated without at least an exclusive (LCK_M_X) table lock. If the delete operation does not use a table lock, the table (heap) will contain many empty pages. For indexes, the delete operation can leave empty pages behind, although these pages will be deallocated quickly by a background cleanup process.

As with DELETE, the definition of a table emptied using TRUNCATE TABLE remains in the database, together with its indexes and other associated objects. If the table contains an identity column, the counter for that column is reset to the seed value that is defined for the column. If no seed was defined, the default value 1 is used. To retain the identity counter, use DELETE instead.

Truncating Large Tables

Microsoft SQL Server introduced the ability to drop or truncate tables that have more than 128 extents without holding simultaneous locks on all the extents required for the drop. For more information, see Dropping and Rebuilding Large Objects.

Examples

The following example removes all data from the JobCandidate table. SELECT statements are included before and after the TRUNCATE TABLE statement to compare results.


    USE AdventureWorks2008R2;
    GO
    SELECT COUNT(*) AS BeforeTruncateCount 
    FROM HumanResources.JobCandidate;
    GO
    TRUNCATE TABLE HumanResources.JobCandidate;
    GO
    SELECT COUNT(*) AS AfterTruncateCount 
    FROM HumanResources.JobCandidate;
    GO