Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimizing Delete on SQL Server

Tags:

sql

sql-server

Deletes on sql server are sometimes slow and I've been often in need to optimize them in order to diminish the needed time. I've been googleing a bit looking for tips on how to do that, and I've found diverse suggestions. I'd like to know your favorite and most effective techinques to tame the delete beast, and how and why they work.

until now:

  • be sure foreign keys have indexes

  • be sure the where conditions are indexed

  • use of WITH ROWLOCK

  • destroy unused indexes, delete, rebuild the indexes

now, your turn.

like image 381
pomarc Avatar asked Jun 05 '09 11:06

pomarc


People also ask

How do I make SQL Server delete faster?

If you are deleting 95% of a table and keeping 5%, it can actually be quicker to move the rows you want to keep into a new table, drop the old table, and rename the new one. Or copy the keeper rows out, truncate the table, and then copy them back in.

How do you delete 10000 records in SQL?

If you need to remove 10 million rows and have 1 GB of log space available use Delete TOP(10000) From dbo. myTable (with your select clause) and keep running it till there are no more rows to delete.

How do I delete a large number of records in SQL?

If you want to delete the records of a table with a large number of records but keep some of the records, You can save the required records in a similar table and truncate the main table and then return the saved records to the main table.


1 Answers

The following article, Fast Ordered Delete Operations may be of interest to you.

Performing fast SQL Server delete operations

The solution focuses on utilising a view in order to simplify the execution plan produced for a batched delete operation. This is achieved by referencing the given table once, rather than twice which in turn reduces the amount of I/O required.

like image 73
John Sansom Avatar answered Sep 18 '22 10:09

John Sansom