0

I've got a procedure with a Sort operator of 92%. Here is the execution plan: enter image description here here is the script:

CREATE   PROCEDURE [Specification].[GetSpecificationsByPage]  
(  
  @Next int,  
        @Limit int  
)  
AS  
BEGIN  
 SELECT   
 ps.Id
 psdc.Timestamp,  
 ps.CreationStatusId,  
 ps.ErrorReason  
 FROM   
 [Specification].[Specifications] ps WITH (NOLOCK)   
 OUTER APPLY (SELECT TOP 1 psd.Timestamp  
      FROM Specification.SpecificationDetails psd  WITH (NOLOCK)  
      WHERE psd.SpecificationId =  ps.Id  
      ORDER BY psd.Timestamp) psdc  
  
 ORDER BY ps.[Id] asc  
 offset @Next rows  
 fetch next @Limit rows only  
END  

I've added an index for column SpecificationId for table :Specification.SpecificationDetails that includes column: Timestamp even added index for Timestamp asc but it still have the cost of 92%.

The only way i've got is to replace to : ORDER BY ps.Id or remove the line in the select: psdc.Timestamp

what index do i need to continute?

6
  • 3
    Have you tried a composite index on Specification.SpecificationDetails(Id, Timestamp)? Be aware than NOLOCK can cause rows to get missed or duplicated during scans, causing wrong results.
    – Dan Guzman
    Commented Jan 7 at 12:40
  • Thanks forgot that option.
    – dexon
    Commented Jan 7 at 13:35
  • 1
    Does the Timestamp column allow duplicate values? If so, you may need to add Id as a secondary ordering element to get deterministic results, though with all the NOLOCK hints you seem to not care about result correctness anyway. Commented Jan 7 at 16:29
  • Your query runs in 0s. Why do you want to make your database do more work maintaining an index at no additional performance gains for this query?
    – J.D.
    Commented Jan 7 at 20:24
  • The Timestamp column is not unique. about the 0s it's a performance issue, it runs in 60ms and has execution count of 20K in an hour.
    – dexon
    Commented Jan 8 at 9:49

1 Answer 1

3

The SORT operator after each seek iteration can be avoided with a composite index:

CREATE INDEX IX_SpecificationDetails_Id_Timestamp ON 
    Specification.SpecificationDetails(Id, Timestamp);

The leftmost Id in the index key will facilitate the seek (as in the current plan). The Timestamp key column will allow an ordered scan in the seek operator, eliminating the need for a subsequent SORT to satisfy the TOP 1...ORDER BY Timestamp criteria.

Your Answer

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

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