SQL Truncate Table - How to use TRUNCATE command in SQL ?



Truncate a Table in SQL

  • Below is a selection from the wikitechytable table used in the examples:
truncate-table-1

  • TRUNCATE statement is used to remove all the rows from a table, effectively deleting all data within that table.
  • DELETE statement removes one row at a time and generates individual log entries for each row deleted.
  • But, TRUNCATE is a minimally logged operation that deallocates data pages and logs only the deallocations of the data pages.
  • This makes TRUNCATE much faster than DELETE for removing all rows from a table.

Syntax

  TRUNCATE TABLE  table_name;
  • Where table_name is the name of the table from which you want to remove all rows. You need the appropriate permissions to execute the TRUNCATE statement on a table.

Keep in mind the following important points about TRUNCATE:

  • Data Preservation:
    • Unlike DELETE, TRUNCATE does not generate individual row-level delete operations. It effectively removes all data from the table but does not preserve or return the deleted data. Once you truncate a table, the data is gone, and you cannot roll it back.
  • Constraints and Triggers:
    • TRUNCATE removes all rows from the table, but it does not activate any DELETE triggers on the table. It also does not check referential integrity constraints, so you must ensure that you're not violating any foreign key relationships with other tables when using TRUNCATE.
  • Identity Columns:
    • If the table has an identity column, TRUNCATE will reset the identity seed to its initial value.
  • Permissions:
    • You need appropriate permissions on the table to execute TRUNCATE.

SQL TRUNCATE TABLE Example

  • The following SQL statement removes all the rows in the existing table "wikitechytable":
  •  TRUNCATE TABLE  wikitechytable;
    
  • Remember to use TRUNCATE with caution, as it can quickly remove all data from a table without the possibility of recovery. If you need to delete specific rows or need to preserve data, consider using the DELETE statement instead.

Output

truncate-table-2

Related Searches to SQL Truncate Table - How to use TRUNCATE command in SQL ?