Truncate Table Within Transaction
Asked Answered
H

3

73

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.

Hallerson answered 5/10, 2009 at 23:36 Comment(2)
I should have clarified that I am using MSSQL 2005 server.Hallerson
This lists all the commands that can NOT be used in a SQL Server transaction. TRUNCATE is not listed, so it is allowed.Amarelle
P
76

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

Plainspoken answered 5/10, 2009 at 23:44 Comment(0)
T
24

In Oracle, TRUNCATE TABLE is a DDL statement that cannot be used in a transaction (or, more accurately, cannot be rolled back). AFAIK, if there is a transaction in progress when the statement is executed, the transaction is committed and then the TRUNCATE is executed and cannot be undone.

In Informix, the behaviour of TRUNCATE is slightly different; you can use TRUNCATE in a transaction, but the only statements permissible after that are COMMIT and ROLLBACK.

Other DBMS probably have their own idiosyncratic interpretations of the behaviour of TRUNCATE TABLE.

Thermopile answered 5/10, 2009 at 23:49 Comment(1)
This is still true for Oracle 21cSupererogate
F
1

If you read the official documentation of PostgreSQL, It said that The TRUNCATE TABLE statement is transaction-safe.

Fusionism answered 21/2, 2023 at 15:3 Comment(1)
The author is referring to MSSQL, not Postgre. This specific topic could differ between the two.Crier

© 2022 - 2024 — McMap. All rights reserved.