TRUNCATE TABLE

Note: TRUNCATE TABLE is a Data Manipulation Language (DML) statement that removes all rows from a table, but the table structure remains intact. It's generally faster than DELETE for removing all rows from a large table.

Description

The TRUNCATE TABLE statement is used to quickly remove all records from a table. Unlike the DELETE statement, TRUNCATE TABLE is not logged for each deleted row, making it a much faster operation, especially for large tables. It deallocates the data pages used by the table, resetting the table to its initial state (as if it were newly created), but without dropping the table itself.

Syntax


TRUNCATE TABLE table_name [WITH ( option_name [ ,...n ] )]

-- Example:
TRUNCATE TABLE Customers;

-- Example with option to preserve identity seed:
TRUNCATE TABLE Orders WITH (TRUNCATE_ONLY); -- This is a hypothetical option for demonstration. Actual options vary by RDBMS.
            

Parameters

Behavior and Differences from DELETE

Tip: Use TRUNCATE TABLE when you need to empty a table completely and quickly, and you don't need to execute any row-level triggers.

When to Use TRUNCATE TABLE

Considerations

Example Scenarios

Clearing a staging table:

Before loading new data into a staging table, you might want to clear its previous contents:


BEGIN TRANSACTION;
TRUNCATE TABLE StagingData;
-- Load new data into StagingData here
COMMIT TRANSACTION;
            

Resetting a table with identity:

If you want to start inserting new records with the first identity value again:


TRUNCATE TABLE UserAccounts;
-- New inserts will start with UserID = 1 (assuming it's the starting seed)
            
Important: Ensure you have proper backups and understand the implications before executing TRUNCATE TABLE on production data.