HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Single statement or batched delete?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
deletesinglebatchedstatement

Problem

I need to delete 6.3 million records from 25 tables in production. I have the following two queries, but I don't know which one will be best:

delete jc 
from Jtable jc
join J1Table j 
on j.JobId = jc.JobId 
join nonJobReProcess n
on n.jobid = j.JobId


or:

while exists (select top 1 * from dbo.Jtable jc (nolock)
join J1Table j (nolock)
on j.JobId = jc.JobId 
join nonJobReProcess  n  (nolock)
on n.jobid = j.JobId)
begin 

delete  top (10000) jc 
from dbo.Jtable jc (nolock)
join J1Table j (nolock)
on j.JobId = jc.JobId 
join nonJobReProcess n  (nolock)
on n.jobid = j.JobId

end


Please explain the reasons I might choose one over the other, or any alternative methods.

Solution

Using the second method will result in less locking, transaction log usage and Tempdb resources, because SQL Server doesn't have to perform all of the delete operations in one transaction.

However, instead of the "while exists" statement, you can use a variable that will get the value of @@rowcount after the delete. This can help a little more with performance.

Context

StackExchange Database Administrators Q#58707, answer score: 3

Revisions (0)

No revisions yet.