What Does Truncate Table Do In SQL Server
[SQL Server, Database]
If you have a large amount of data in a SQL Server table and want to quickly purge it, one way is to truncate the table using the TRUNCATE command.
TRUNCATE TABLE Users
This will quickly purge the table.
The caveat is that it only works under the following conditions:
- The table has no foreign keys
- The table is participating in replication
- The table is being used in an indexed view
You must also keep in mind the following considerations:
If this is in order, then you can truncate the table.
What happens internally is the following:
- Data pages are de-allocated
- Minimal logging takes place
This frees the database engine from the extensive work of doing row-by-row logging.
Another thing to keep in mind is that you can wrap TRUNCATE statements in transactions, meaning that ROLLBACK and COMMIT work.
In other words, the following statements will reset the Users table to its original state.
BEGIN TRAN
TRUNCATE TABLE Users
ROLLBACK
In terms of security considerations, the user running the TRUNCATE command requires ALTER TABLE permissions.
TLDR
TRUNCATE is a quick way to empty a database table, provided it meets the criteria for truncation.
Happy hacking!