I have a table that stores the relationship between parents and children. They can change over time, and you need to keep a complete history so that I can ask how the relationship was at any time.
There is something like this in the table (I deleted several columns, primary key, etc. to reduce noise):
CREATE TABLE [tblRelation]( [dtCreated] [datetime] NOT NULL, [uidNode] [uniqueidentifier] NOT NULL, [uidParentNode] [uniqueidentifier] NOT NULL )
My query for getting relationships at a specific time looks like this (suppose @dt is a date-time with the right date):
SELECT * FROM ( SELECT ROW_NUMBER() OVER (PARTITION BY r.uidNode ORDER BY r.dtCreated DESC) ix, r.* FROM [tblRelation] r WHERE (r.dtCreated < @dt) ) r WHERE r.ix = 1
This query works well. However, performance is still not as good as we would like. Considering the implementation plan, it mainly comes down to clustered index scanning (36% of the cost) and sorting (63% of the cost).
What indexes should be used to speed up this query? Or is there a better way to fulfill this query in this table?
source share