Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete large amount of data in sql server

Suppose that I have a table with 10000000 record. What is difference between this two solution?

  1. delete data like :

    DELETE FROM MyTable
    
  2. delete all of data with a application row by row :

    DELETE FROM MyTable WHERE ID = @SelectedID
    

Is the first solution has best performance? what is the impact on log and performance?

like image 706
masoud ramezani Avatar asked Jan 26 '10 09:01

masoud ramezani


People also ask

How can I delete lakhs of records in SQL Server?

By far, the fastest way to delete a bunch of records is to use the TRUNCATE TABLE statement. This is much faster than the DELETE statement because it does not log any of the row-level delete operations. However, you can only use TRUNCATE TABLE : To delete ALL the records in the table.

How do I purge old data in SQL Server?

To delete rows in a SQL Server table, use the DELETE statement: delete from sessions where id = 10; The WHERE clause is optional, but you'll usually want it, unless you really want to delete every row from the table.


1 Answers

If you need to restrict to what rows you need to delete and not do a complete delete, or you can't use TRUNCATE TABLE (e.g. the table is referenced by a FK constraint, or included in an indexed view), then you can do the delete in chunks:

DECLARE @RowsDeleted INTEGER
SET @RowsDeleted = 1

WHILE (@RowsDeleted > 0)
    BEGIN
        -- delete 10,000 rows a time
        DELETE TOP (10000) FROM MyTable [WHERE .....] -- WHERE is optional
        SET @RowsDeleted = @@ROWCOUNT
    END

Generally, TRUNCATE is the best way and I'd use that if possible. But it cannot be used in all scenarios. Also, note that TRUNCATE will reset the IDENTITY value for the table if there is one.

If you are using SQL 2000 or earlier, the TOP condition is not available, so you can use SET ROWCOUNT instead.

DECLARE @RowsDeleted INTEGER
SET @RowsDeleted = 1
SET ROWCOUNT 10000 -- delete 10,000 rows a time

WHILE (@RowsDeleted > 0)
    BEGIN
        DELETE FROM MyTable [WHERE .....] -- WHERE is optional
        SET @RowsDeleted = @@ROWCOUNT
    END
like image 98
AdaTheDev Avatar answered Sep 20 '22 12:09

AdaTheDev