The TRUNCATE TABLE
statement in MS SQL Server is used to remove all rows from a table quickly and efficiently, without logging individual row deletions. Here’s a rundown of its key features and considerations:
Key Features:
-
Fast Operation:
TRUNCATE TABLE
is generally faster thanDELETE FROM table_name
because it doesn’t generate individual row delete logs; instead, it logs the page deallocations. -
Reset Identity: If the table has an identity column,
TRUNCATE TABLE
will reset the identity value to the seed value defined for the column. -
No Triggers:
TRUNCATE TABLE
does not activate anyDELETE
triggers associated with the table. -
Table Structure Remains: The table structure, including constraints, indexes, and schema, remains intact after truncation.
-
Cannot Truncate if Referenced: You cannot truncate a table that is referenced by a foreign key constraint.
Syntax:
Example:
If you have a table named Employees
and you want to remove all rows, you can use:
Considerations:
-
Permissions: You need
ALTER
permissions on the table to executeTRUNCATE TABLE
. -
Transactions: While
TRUNCATE TABLE
is a minimally logged operation, it can still be rolled back if used within a transaction. For example:BEGIN TRANSACTION;
TRUNCATE TABLE Employees; -- Other operations
ROLLBACK TRANSACTION; -
Foreign Keys: If the table is referenced by foreign keys, you will need to drop or disable those constraints before truncating.
-
Not a Substitute for DELETE: If you need to conditionally delete rows or want to fire triggers, use
DELETE
instead ofTRUNCATE TABLE
.
In summary, TRUNCATE TABLE
is a powerful command for quickly clearing out a table