SQL TRUNCATE TABLE

The TRUNCATE TABLE statement in SQL is used to delete all rows from a table, while retaining the table structure for future use. It is faster than the DELETE statement because it does not log individual row deletions.

Syntax


TRUNCATE TABLE table_name;
            
- table_name: The name of the table to be truncated.

Example

Let us truncate the Staff table:

Code Example


-- Truncate the Staff Table
TRUNCATE TABLE Staff;

-- Display the Empty Table
SELECT * FROM Staff;
                

Output

-- Before TRUNCATE:
ID Name Age Department
2 Bob 25 IT
3 Charlie 35 Finance
-- After TRUNCATE:
ID Name Age Department
(empty set)

Explanation

- The TRUNCATE TABLE command removes all rows from the Staff table but retains its structure.
- The SELECT * statement confirms that the table is empty.

Remember This:

- Use TRUNCATE instead of DELETE when you want to clear all rows quickly.
- Be cautious, as this operation cannot be rolled back if it is not wrapped in a transaction.