0

I have a simple delete query :

Delete from sales
where ImportLogId = @ImportLogid

ImportLog table has around 3 million records with all log details.

I have non clustered index created on ImportLog table on ImportLogID.

The fragementation is less than 10% but still the query is taking more time to execute but when I rebuild the index manually it is executed within a second. After a day the same problem repeats. Rebuilding the index using code doesn't seems to help but rebuilding index in SQL Server UI helps.

Any difference in rebuilding index using SQL query and manually using UI? why does the index with less fragmentation also takes more time to execute whereas when I rebuild the index it executes within a second?

  • Page fullness is 99.71 %
  • Total Fragementation is 4%

Looking for a better solution

please find the execution plan below

7
  • Any difference in rebuilding index using SQL query and manually using UI No, SSMS uses tsql commands to do everything. Diagnosis starts by comparing the execution plans - and giving some ideas about the percentage of rows you are deleting vs. the total number of rows. DDL for the table would be useful as well.
    – SMor
    May 10, 2022 at 11:29
  • when the fragmentation % is less , how does rebuilding the index solves my issue ? is it fine to rebuild the index every time the stored procedure is executed ?
    – john
    May 10, 2022 at 11:42
  • Hi @john. You're not giving us a lot to work with here - please use pastetheplan.com. How many rows are there per ImportLogid?
    – mikkel
    May 10, 2022 at 13:06
  • try with a clustered index instead of a NONCLUSTERED one !
    – SQLpro
    May 10, 2022 at 13:54
  • 1
    ah, your comment was hidden before i posted my answer, but I guess I answer your second question as to why it is necessary to index the foreign key: Referential Integrity. You're not allowed to delete rows that are referenced elsewhere, and the only way for Sql Server to enforce this is to check the references. If the only index containing ImportSalesId is the clustered (PK_WholesalerSale) then a scan of this index is required.
    – mikkel
    May 11, 2022 at 10:44

1 Answer 1

1

Right. So your problem is not the deletion of records, which is instantaneous. (84 rows). The problem is the scan on the WholesalerSale table afterwards.

My guess would be, that ImportSale.Id is a foreign key in WholesalerSale, and that SqlServer simply validates that you haven't deleted a referenced key.

Solution is to index your foreign key column in WholesalerSale to speed up this check.

CREATE INDEX IX_WholesalerSale_ImportSaleId ON WholesalerSales (ImportSaleId);
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.