Jump to content

Truncate (SQL)

From Wikipedia, the free encyclopedia

InSQL,theTRUNCATE TABLEstatement is aData Manipulation Language(DML) operation that deletes all rows of a table without causing a triggered action.[1]The result of this operation quickly removes all data from atable,typically bypassing a number of integrity enforcing mechanisms. It was officially introduced in theSQL:2008standard, as the optional feature F200, "TRUNCATE TABLE statement".

TRUNCATE TABLE removes all rows from a table, but the table structure and its columns, constraints, indexes, and so on remain. To remove the table definition in addition to its data, use theDROP TABLEstatement.

TheTRUNCATE TABLE mytablestatement is logically (though not physically) equivalent to theDELETEFROM mytablestatement (without aWHEREclause). The following characteristics distinguishTRUNCATE TABLEfromDELETE:

  • In theOracle Database,TRUNCATEis implicitly preceded and followed by acommitoperation. (This may also be the case inMySQL,when using a transactional storage engine.)
  • Typically,TRUNCATE TABLEquickly deletes all records in a table by deallocating the data pages used by the table. This reduces the resource overhead ofloggingthe deletions, as well as the number oflocksacquired. Records removed this way cannot be restored in a rollback operation. Two notable exceptions to this rule are the implementations found inPostgreSQLandMicrosoft SQL Server,both of which allowTRUNCATE TABLEstatements to be committed or rolled back transactionally.
  • It is not possible to specify aWHEREclause in aTRUNCATE TABLEstatement.
  • TRUNCATE TABLEcannot be used when a foreign key references the table to be truncated, sinceTRUNCATE TABLEstatements do not firetriggers.This could result in inconsistent data becauseON DELETE/ON UPDATEtriggers would not fire.
  • In some computer systems,TRUNCATE TABLEresets the count of anIdentity columnback to the identity'sseed.
  • InMicrosoft SQL Server2000 and beyond in full recovery mode, every change to the database is logged, soTRUNCATE TABLEstatements can be used for tables involved inlog shipping.[2]

References[edit]

  1. ^"ISO/IEC 9075 Database languages SQL".iso.org.Retrieved4 June2023.
  2. ^"Description of the effects of nonlogged and minimally logged operations on transaction log backup and the restore process in SQL Server".Microsoft. December 2005.