I have a table with the following schema:
AccountId: int
StartDateTime: datetime2(0)
EndDateTime: datetime2(0)
I want to be able to query this for rows with a certain AccountId, and whose date range intersects with a specified date range. E.g:
SELECT *
FROM ... AS d
WHERE d.AccountId = @AccountId
AND d.StartDateTime <= @EndDateTime
AND d.EndDateTime >= @StartDateTime
This will be a very large table and I'll want to be able to query it as efficiently as possible. I've specified a single composite index of AccountId, StartDateTime, and EndDateTime.
Will this index, and the above query work effectively together? If not, what would be a better alternative? Thanks.
d.EndDateTime >= @StartDateTimethen the second column in the index should beEndDateTimelike this:CREATE UNIQUE NONCLUSTERED INDEX [idx_Table1_AccountID_End_Start] ON [dbo].[Table1] ( [AccountId] ASC, [EndDateTime] ASC, [StartDateTime] DESC )– Sabin B Jul 15 '15 at 20:06AccountIdis the primary key (default sql server will create a clustered index), then for the query you have specified wont even need an additional index (just having 3 columnsaccountid,startdateTime,enddatetime). It will do an Index seek. Also, you should not useselect *, instead explicitly specify column names. – Kin Shah Jul 15 '15 at 20:59accountIdto precede any other index columns (assuming that you will always be querying a singleaccountIdout of many accountIds overall) – Geoff Patterson Jul 15 '15 at 23:34