For the below query, I'm trying to figure out why the index suggested by SQL Server on the sysjobhistory table, which is also the index that results in a seek, was created on the Job_Id column with the other columns included:
Job_Id includes (Run_date, Run_time, Instance_id)
To my understanding, columns in a where clause should be present in the index key for seeks to be possible. Run_date and Run_time are present in the where clause of the below query, so how come we can get away with putting them in the include of an index rather than have them as key columns?
The query:
SELECT TOP 10000 run_date
FROM msdb.dbo.sysjobhistory sh
WHERE EXISTS (SELECT 1 FROM msdb.dbo.sysjobs sj WHERE sh.job_id = sj.job_id
AND EXISTS (SELECT 1 FROM msdb.dbo.sysjobschedules sjs WHERE sjs.job_id = sj.job_id
AND EXISTS (SELECT 1 FROM msdb.dbo.sysschedules ss WHERE ss.schedule_id = sjs.schedule_id
AND ss.freq_subday_type = 2
AND ss.freq_subday_interval = 10 )))
AND CAST(CAST([run_date] AS CHAR(8)) + ' ' + STUFF(STUFF(RIGHT('000000' + CAST([run_time] AS VARCHAR(6)), 6), 3, 0, ':'), 6, 0, ':') AS DATETIME) < dateadd(hh,-12,getdate())
Note: I'm not using joins because this query is part of a cte that I then delete from, so joins are not possible.