SQL Server: Delete in batches

When there’s a large amount of data to be deleted, the performance of SQL suffers a lot. One way around it is to delete in batches, for example 10 000 rows at a time.

Instead of :
delete from yourtable where [condition]

i’d use:

— set rowcount to delete sets of 10 000 records (use a smaller subset size if you think it’s better)
set rowcount 10000
— start delete
delete from yourtable where
while @@rowcount > 0 — loop until there’s no record left to delete
begin
— after each delete there will be an implicit commit
delete from yourtable where
end

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s