Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate Table Within Transaction

Can the SQL "truncate table" command be used within a transaction? I am creating an app and my table has a ton of records. I want to delete all the records, but if the app fails I was to rollback my transaction. Deleting each record takes a very long time. I'm wondering if I use truncate table, can I still rollback the transaction and get my data back in the event of a failure. I realize that truncate table doesn't write each delete to the transaction log, but I'm wondering if it writes the page deallocation to the log so that rollback works.

like image 876
Davin Studer Avatar asked Oct 05 '09 23:10

Davin Studer


People also ask

Can you truncate a table in a transaction?

In Oracle, TRUNCATE TABLE is a DDL statement that cannot be used in a transaction (or, more accurately, cannot be rolled back).

Can we truncate a table which is participating in transactional replication?

Truncate cannot be used in certain cases like replication / foreign key contraints, etc. As per Microsoft documentation you need to use delete. You cannot use TRUNCATE TABLE on tables that: Are referenced by a FOREIGN KEY constraint.

Can truncate be rolled back in transaction?

When you execute a Truncate statement, it does not get logged in the log file as it is a DDL statement. So if you Truncate a table, you cannot Roll Back to a point in time before the truncate. However, in a Transaction, Rollback is permitted and functions just as any other rollback would.

Can you alter table in a transaction?

Yes, it is possible to use many ALTER TABLE statements in one transaction with ROLLBACK and COMMIT .


1 Answers

In SQL Server, you can rollback a TRUNCATE from a transaction. It does write page deallocation to the log, as you mentioned.

like image 143
womp Avatar answered Oct 02 '22 21:10

womp