This query is taking 5 seconds:
With cte as
(
Select ROW_NUMBER() OVER (Order By dbo.GetLatestStatusDateTime(d.DocumentID)) peta_rn, d.DocumentID, d.IsReEfiled, d.IGroupID, d.ITypeID, d.RecordingDateTime,
d.IDate, d.InstrumentID, d.DocumentStatusID, u.Username, j.JDAbbreviation, inf.DocumentName, dbo.GetLatestStatusDateTime(d.DocumentID) as LatestStatusDatetime,
it.Abbreviation as ITypeAbbreviation, d.DocumentDate, ds.Abbreviation as DocumentStatusAbbreviation
From Documents d Left Join IGroupes ig On d.IGroupID = ig.IGroupID
Left Join ITypes it On d.ITypeID = it.ITypeID
Left Join Users u On u.UserID = d.UserID
Left Join DocumentStatuses ds On d.DocumentStatusID = ds.DocumentStatusID
Left Join InstrumentFiles inf On d.DocumentID = inf.DocumentID
Left Join Jurisdictions j on j.JurisdictionID = d.JurisdictionID Where 1 = 1 And d.JurisdictionID = 1
)
Select * from cte
Where 1 = 1
And peta_rn>92000 AND peta_rn<=92100
Though this is a static query, it will be dynamic in the sense that Order By in Row_Number() would be based on what user selects. Eg. currently it is dbo.GetLatestStatusDateTime(d.DocumentID) but it can be anything else too. Hence this query would be generated in code using if and then. Anyways, can you spot any mistake in my query? Why would it take 5 seconds for mere 100 records? I have seen SQL server scale upto millions of records and this is just 1/10th of million and I am suffering from bottleneck 🙁
Edit: Massive improvement
Changing the query to this:
With cte as
(
Select ROW_NUMBER() OVER (Order By d.DocumentID) peta_rn, d.DocumentID
From Documents d Left Join IGroupes ig On d.IGroupID = ig.IGroupID
Left Join ITypes it On d.ITypeID = it.ITypeID
Left Join Users u On u.UserID = d.UserID
Left Join DocumentStatuses ds On d.DocumentStatusID = ds.DocumentStatusID
Left Join InstrumentFiles inf On d.DocumentID = inf.DocumentID
Left Join Jurisdictions j on j.JurisdictionID = d.JurisdictionID Where 1 = 1 And d.JurisdictionID = 1
)
Select d.DocumentID, d.IsReEfiled, d.IGroupID, d.ITypeID, d.RecordingDateTime,
d.IDate, d.InstrumentID, d.DocumentStatusID, u.Username, j.JDAbbreviation, inf.DocumentName,
it.Abbreviation as ITypeAbbreviation, d.DocumentDate, ds.Abbreviation as DocumentStatusAbbreviation
From Documents d Left Join IGroupes ig On d.IGroupID = ig.IGroupID
Left Join ITypes it On d.ITypeID = it.ITypeID
Left Join Users u On u.UserID = d.UserID
Left Join DocumentStatuses ds On d.DocumentStatusID = ds.DocumentStatusID
Left Join InstrumentFiles inf On d.DocumentID = inf.DocumentID
Left Join Jurisdictions j on j.JurisdictionID = d.JurisdictionID
Inner Join cte On cte.DocumentID = d.DocumentID
And peta_rn>92000 AND peta_rn<=92100
executes the query in 1 second. But I still feel 1 second is too big just for 100 records. Any other optimizations please?
try this. It is alot of code to edit without knowing the tables relations and not being able to test it. I hope this helps.