69

Could someone give me a quick overview of the pros and cons of using the following two statements:

TRUNCATE TABLE dbo.MyTable

vs

DELETE FROM dbo.MyTable

It seems like they both do the same thing when all is said and done; but are there must be differences between the two.

Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275
Jim B
  • 8,344
  • 10
  • 49
  • 77

11 Answers11

96

TRUNCATE doesn't generate any rollback data, which makes it lightning fast. It just deallocates the data pages used by the table.

However, if you are in a transaction and want the ability to "undo" this delete, you need to use DELETE FROM, which gives the ability to rollback.

EDIT: Note that the above is incorrect for SQL Server (but it does apply to Oracle). In SQL Server, it is possible to rollback a truncate operation if you are inside a transaction and the transaction has not been committed. From a SQL Server perspective, one key difference between DELETE FROM and TRUNCATE is this: "The DELETE statement removes rows one at a time and records an entry in the transaction log for each deleted row. TRUNCATE TABLE removes the data by deallocating the data pages used to store the table data and records only the page deallocations in the transaction log."

In other words, there is less logging during a TRUNCATE because only the page deallocations are recorded in the transaction log, whereas with a DELETE FROM each row deletion is recorded. That's one of the reasons TRUNCATE is lightning fast.

Note also from that MSDN link that you cannot truncate tables that are referenced by foreign key constraints, participate in an indexed view, or are published by using transactional replication or merge replication.

EDIT 2: Another key point is that TRUNCATE TABLE will reset your identity to the initial seed, whereas DELETE FROM will carry on incrementing from where it left off. Reference: Ben Robinson's answer.

Fletch
  • 367
  • 1
  • 5
  • 20
dcp
  • 54,410
  • 22
  • 144
  • 164
  • 7
    `TRUNCATE` may also break consistency (=doesn't check for foreign keys, and doesn't fire triggers) – nothrow Jul 15 '10 at 14:04
  • 17
    @Yossarian - According to MSDN: "You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint; instead, use DELETE statement without a WHERE clause". http://msdn.microsoft.com/en-us/library/aa260621%28SQL.80%29.aspx – dcp Jul 15 '10 at 14:07
  • 4
    truncate can alos be rolled backed. http://sqlblog.com/blogs/denis_gobo/archive/2007/06/13/1458.aspx – Dhananjay Jul 09 '12 at 13:10
  • 1
    @Dhananjay - Not always: http://blog.sqlauthority.com/2007/12/26/sql-server-truncate-cant-be-rolled-back-using-log-files-after-transaction-session-is-closed/ – dcp Aug 08 '12 at 12:48
  • @dcp: yes. Thats true. I was telling that "truncate cann't be rolled back" is not 100% true statement. – Dhananjay Aug 08 '12 at 19:17
  • If You want to apply truncate on a table referenced by a Foreign key then you can also do it by removing the Foreign key Constraint and then truncate and then reapply the Foreign key constraint. – khalid khan Apr 26 '14 at 11:00
  • This accepted answer is wrong. TRUNCATE is a fully logged operation and can be rolled back just like DELETE or any other operation. The perceived "lightning fast" operation of TRUNCATE is due to deferred (asynchronous) logging not due to a lack of "rollback data". The "sqlauthority" article mentioned is misleading but the comments on that blog do point out that TRUNCATEd data can be restored from a point-in-time restore of the log file, just as DELETEs can be. – nvogel Jan 19 '15 at 19:18
  • @sqlvogel - Yes, you are right about TRUNCATE being able to be rolled back, thanks for noting this. I have edited the answer. However, I think the "lightning fastness" is due to just data pages being logged instead of every row being logged, which results overall in much less logging. Not sure about the asynchronous part since MSDN didn't mention that. Also, I don't think TRUNCATE can be restored from the log file after the transaction has been committed unless those data pages haven't been reallocated. – dcp Jan 20 '15 at 13:18
  • 1
    MSFT calls it [Deferred Drop](http://technet.microsoft.com/en-us/library/ms177495(v=sql.105).aspx). Page deallocations are logged after the truncate is committed rather than before. This doesn't compromise t-log backup/restore and a log restore is always preceded by a database restore anyway. – nvogel Jan 20 '15 at 21:51
  • Conceivably there may be edge cases where recovery of data is possible from a delete but not from a truncate. I doubt that's an "official" supported scenario though (possibly it might have to involve 3rd party tools or unsupported techniques). The sqlauthority article doesn't explain any of this. Without further info I'm sceptical about the claim that truncated data is not always recoverable (under full recovery model I mean). – nvogel Jan 20 '15 at 21:52
  • @sqlvogel - Thanks for the link on Deferred Drop, I did not know about that. As for the edge cases, I think if the data pages that are freed as a result of the truncate are reallocated to some other table and then written to, then one wouldn't be able to recover them in a restore operation. I would equate it with accidentally deleting a partition on a hard drive. The old data is still "there", until you start overwriting it with new stuff, so it's sometimes possible to recover the partition if you act quickly. Anyway, great discussion. – dcp Jan 20 '15 at 22:32
  • @dcp When you restore to an earlier point in time every allocated page in the database gets restored regardless of its prior state. What happens during and after truncate doesn't matter because the truncated data will always be contained either in the database backup, log backup(s) or the tail portion of the log. – nvogel Jan 20 '15 at 22:57
  • @sqlvogel - Yes, under full recovery mode you'd have a full backup of all those pages so that restore would work fine. But if you only had differential backups, I think you'd have to use some tool like this (http://solutioncenter.apexsql.com/rollback-truncate-operation-without-backups/) to try to get to those data pages. That's the scenario I was thinking of when I referred to the deallocated data pages. I would imagine these tools would try to reconstruct those data pages somehow using the log file. – dcp Jan 21 '15 at 00:35
  • True enough. If your full database backups go up in smoke (or you never made any!) then you will not be in a happy place, third party tools or no third party tools. It seems like a stretch to say that's a disadvantage/limitation of TRUNCATE though because the same could apply equally to other DML operations - DELETE included. If you only have differential backups and the tail log from which to recover data then many/most committed changes will be totally unrecoverable. – nvogel Jan 21 '15 at 11:10
49

Another key point not mentioned in the other answers is that TRUNCATE TABLE will reset your identity to the initial seed, whereas DELETE FROM will carry on incrementing from where it left off.

Ben Robinson
  • 21,601
  • 5
  • 62
  • 79
10

Another difference from a security perspective is that TRUNCATE requires ALTER privileges on the table, while DELETE merely requires (drum roll) DELETE permissions on that table.

Kyle Hale
  • 7,912
  • 1
  • 37
  • 58
6

TRUNCATE TABLE doesn't log the transaction. That means it is lightning fast for large tables. The downside is that you can't undo the operation.

DELETE FROM logs each row that is being deleted in the transaction logs so the operation takes a while and causes your transaction logs to grow dramatically. The upside is that you can undo the operation if need be.

Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
  • 2
    TRUNCATE is logged and can be undone just like DELETE - by using ROLLBACK or RESTORE. – nvogel Jun 29 '11 at 11:29
  • 1
    only if you use transactions, and if the truncate is commited, it cannot be rolled back. it is DDL and not logged to log file. – ScaleOvenStove Jul 12 '11 at 18:00
  • 1
    It is interesting that both this reply and the one marked as answer tell almost the same thing, but this has been downvoted to -1 while the one marked as answer upvoted to +7 (at least at the moment I am writing this). As @dcp previously noted, [this](http://blog.sqlauthority.com/2007/12/26/sql-server-truncate-cant-be-rolled-back-using-log-files-after-transaction-session-is-closed/) is a good article that describes the rollback behavior of TRUNCATE vs DELETE. – Florin Dumitrescu Sep 24 '13 at 20:22
3

Outline of Delete Vs Truncate in SQL server

For Complete Article take after this connection: Delete Vs Truncate in SQL Server

enter image description here

/*Truncate - Syntax*/
TRUNCATE TABLE table_name

/*Delete - Syntax*/
DELETE FROM table_name
WHERE some_condition
Rahul Modi
  • 748
  • 11
  • 21
2

I believe Delete and Truncate can only be rolled back if the operation was executed in and explicit transaction. Otherwise you would have to perform a restore to recover the removed data

CNkatcher
  • 21
  • 1
1

The fundamental difference is in the way they are logged. DELETE and TRUNCATE are logged differently but both can be rolled back in exactly the same way. All operations that change data are logged. In SQL Server there is no such thing as a non-logged operation.

nvogel
  • 24,981
  • 1
  • 44
  • 82
0

One thing that's very important(imo) and not mentioned on other answers is that TRUNCATE needs Schema Stability lock, Sch-S, whereas DELETE uses row locks. Lets inspect the following:

BEGIN TRANSACTION;

BEGIN TRY
    -- Truncate below will take LCK_M_SCH_S lock for TABLE_A
    TRUNCATE TABLE TABLE_A

    -- Lets say the query below takes 5 hours to execute
    INSERT INTO
        TABLE_A
    SELECT
        *
    FROM
        GIANT_TABLE (NOLOCK)
END TRY
BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION;
    THROW
END CATCH

IF @@TRANCOUNT > 0
    COMMIT TRANSACTION;

Now assume that after 1-2 minutes of the start of this query, let's say we tried to execute the following:

SELECT COUNT(*) FROM TABLE_A (NOLOCK)

Notice that I used NOLOCK clause. What do you think will happen now? This query will wait 5 hours. Why? Because NOLOCK clause needs Sch-S lock on TABLE_A but that TRUNCATE clause has Sch-S on it already. Since we didn't commit the transaction yet, the lock is still on even after that TRUNCATE clause. Sch-S lock on a table basically means that either TABLE_A is being altered by adding/removing columns etc. or it's being truncated. You even can't execute something like below:

SELECT object_id('TABLE_A')

This will stuck 5 hours too. However, if you replace that TRUNCATE with DELETE FROM, you'll see that there will be no Sch-S lock on the table and the queries above will not get stucked.

yakya
  • 4,559
  • 2
  • 29
  • 31
0

Another difference between DELETE vs TRUNCATE is behaviour when table is corrupted.

For instance:

DELETE FROM table_name;

Will end up with error:

Msg 3314, Level 21, State 3, Line 1

During undoing of a logged operation in database '...', an error occurred at log record ID (). Typically, the specific failure is logged previously as an error in the Windows Event Log service. Restore the database or file from a backup, or repair the database.

Msg 0, Level 20, State 0, Line 0

A severe error occurred on the current command. The results, if any, should be discarded.

While TRUNCATE will work:

TRUNCATE TABLE table_name;
-- Command(s) completed successfully.
Community
  • 1
  • 1
Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275
0

Plus all the answers, another point to consider that Truncate will not trigger the delete trigger of the table, but delete statement will trigger the delete trigger of the table for each row.

Melad Basilius
  • 3,847
  • 10
  • 44
  • 81
-2

truncate doesnt do any logging, delete does, so if you have a ton of records, your trans log is huge

ScaleOvenStove
  • 760
  • 1
  • 7
  • 11