SQL Server Tutorialprovides basic and advanced concepts of C# for beginners and professionals.

SQL TRUNCATE TABLE

Back to: SQL Server Tutorial

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:

  1. Fast Operation: TRUNCATE TABLE is generally faster than DELETE FROM table_name because it doesn’t generate individual row delete logs; instead, it logs the page deallocations.

  2. Reset Identity: If the table has an identity column, TRUNCATE TABLE will reset the identity value to the seed value defined for the column.

  3. No Triggers: TRUNCATE TABLE does not activate any DELETE triggers associated with the table.

  4. Table Structure Remains: The table structure, including constraints, indexes, and schema, remains intact after truncation.

  5. Cannot Truncate if Referenced: You cannot truncate a table that is referenced by a foreign key constraint.

Syntax:

TRUNCATE TABLE table_name;

Example:

If you have a table named Employees and you want to remove all rows, you can use:

TRUNCATE TABLE Employees;

Considerations:

  • Permissions: You need ALTER permissions on the table to execute TRUNCATE 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 of TRUNCATE TABLE.

In summary, TRUNCATE TABLE is a powerful command for quickly clearing out a table

Scroll to Top