Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DELETE performance in SQL Server on clustered index, large table

I have a table with more than 20 million rows, and when i do:

DELETE [Table] WHERE ID = ?

It takes over 40 seconds. The ID column is clustered.

Is this what you could expect? or is it possible to optimize this?

like image 904
Erik Sundström Avatar asked Jun 20 '11 11:06

Erik Sundström


People also ask

Is delete faster with index?

Indexes can make every operation in the database faster, even deletes.

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.

Does clustering index enhance the query performance?

Clustering indexes can improve the performance of most query operations because they provide a more linear access path to data, which is stored in pages. In addition, because rows with similar index key values are stored together, sequential detection prefetching is more efficient when clustering indexes are used.


2 Answers

In addition to the fine points JNK included in their answer, one particular killer I've seen is when you're deleting rows from the referenced table for one or more foreign key constraints, and the referencing column(s) in the referencing table(s) aren't indexed - you're forcing a table scan on each of those tables to occur before the delete can be accepted.

like image 72
Damien_The_Unbeliever Avatar answered Sep 30 '22 15:09

Damien_The_Unbeliever


Also try deleting data in a batch. Example

set rowcount 10000
delete [table] where id = ? 
while @@rowcount >0
begin
delete [table] where id = ? 
end
like image 25
Madhivanan Avatar answered Sep 30 '22 16:09

Madhivanan