SQL Myth: Truncate table can not be rolled back

SQL Myth: Truncate table can not be rolled back

I heard this one again last week, and I’m not sure why it’s still going around. Microsoft changed the behavior of Truncate Table to be able to be rolled back, but this myth had been taught to DBAs for so many years, that I think some haven’t tried it.

Very simply, Truncate Table can be rolled back since SQL Server 2005.

Let’s start by looking at the reasons for the inability to roll back a Truncate Table statement. In the late-Sybase/early-SQL Server days through SQL Server 2000, Truncate Table actually dropped the table and created a new one. This moved Truncate Table from pure DML, which is what we expect, to a combined DML/DDL statement, which could not be rolled back. This is seen by looking at the Object_ID for the table, and seeing that a new Object_ID is created during the Truncate Table statement.

Beginning with SQL Server 2005, Truncate Table does not drop and create, but rather unlinks the page list from the table. This unlinking is now logged, and can be rolled back using a standard transaction.

Let’s take a look at this in my trusty Sandbox database.

We’ll start by dropping the table if it exists, and creating a new one.

Truncate 1 - SQL Myth: Truncate table can not be rolled back

A quick Select will show the empty table.

Truncate 2 - SQL Myth: Truncate table can not be rolled back
truncate 3 - SQL Myth: Truncate table can not be rolled back

Now, let’s add some data and view it.

truncate 4 - SQL Myth: Truncate table can not be rolled back
truncate 5 - SQL Myth: Truncate table can not be rolled back

Now, let’s truncate the table within a transaction and verify that the data is gone.

Truncate 6 - SQL Myth: Truncate table can not be rolled back
truncate 7 - SQL Myth: Truncate table can not be rolled back

A Rollback will bring the data back.

truncate 8 - SQL Myth: Truncate table can not be rolled back
truncate 9 - SQL Myth: Truncate table can not be rolled back

So, as you can see, the Rollback restored the data.

See also  🔙 Undo changes to IIS with Configuration History

The source code for this article is attached to this article.

whoami
Stefan Pejcic
Join the discussion

I enjoy constructive responses and professional comments to my posts, and invite anyone to comment or link to my site.