TRUNCATE TABLE Statement

Course- SQL >

This SQL tutorial explains how to use the SQL TRUNCATE TABLE statement with syntax and examples.

Description

The SQL TRUNCATE TABLE statement is used to remove all records from a table. It performs the same function as a DELETE statement without a WHERE clause.

Warning: If you truncate a table, the TRUNCATE TABLE statement can not be rolled back in some databases.

Syntax

The syntax for the SQL TRUNCATE TABLE statement is:

TRUNCATE TABLE table_name;

Parameters or Arguments

table_name
The table that you wish to truncate.

Example

You might choose to truncate a table instead of dropping the table and recreating it. Truncating a table can be faster and does not affect any of the table's indexes, triggers, and dependencies. It is also a fast way to clear out the records from a table if you don't need to worry about rolling back.

Let's look at an example of how to use the TRUNCATE TABLE statement in SQL.

For example:

TRUNCATE TABLE suppliers;

This example would truncate the table called suppliers and remove all records from that table.

It would be equivalent to the following DELETE statement in SQL:

DELETE FROM suppliers;

Both of these statements would result in all data from the suppliers table being deleted. The main difference between the two is that you can roll back the DELETE statement if you choose, but you can't roll back the TRUNCATE TABLE statement.

Let's look at one more example where we prefix the table name with the database name.

For example:

TRUNCATE TABLE totn.contacts;

This example would truncate the table called contacts in the database called totn.