Tuning of a delete query causing slowness

mo boy 396 Reputation points
2024-02-14T08:30:02.2333333+00:00

Dear Experts, There is a delete statement which is causing considerable slowness on the server and it runs after hours. Please provide recommendations to tune this query. The primary key is there on this HostNTEvent_TimeGenerated column.

delete  FROM [MyDB].[dbo].[tbl_HostNTEvent] 
where [HostNTEvent_TimeGenerated] < dateadd(day,-30,getdate())
and HostNTEvent_EventCode not in(4407, 4003)

The select statement below returns around 10 millions rows.

select count(*)  from  [MyDB].[dbo].[tbl_HostNTEvent] 
where [HostNTEvent_TimeGenerated] < dateadd(day,-30,getdate())
and HostNTEvent_EventCode not in(4407, 4003)

Thanks,

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
13,784 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,637 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Olaf Helper 44,501 Reputation points
    2024-02-14T08:39:24.9333333+00:00

    There is not much you could optimize, it takes some time to delete data, which always cause an update in existing indexes as well. You could delete the data batch wise, let's say alway 10,000 records per batch =>

    delete TOP (10000)  FROM [MyDB].[dbo].[tbl_HostNTEvent] 
    where [HostNTEvent_TimeGenerated] < dateadd(day,-30,getdate())
    and HostNTEvent_EventCode not in(4407, 4003)
    GO 1000
    
    

  2. LiHongMSFT-4306 27,016 Reputation points
    2024-02-15T03:15:20.83+00:00

    Hi @mo boy

    Please check if the performance is poor due to physical I/O.

    Check if exists deadlocks or blocking.

    If exists cascade delete or triggers.

    Best regards,

    Cosmog Hong


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.