I try to optimize index usage in some of the queries I use often. Recently I have learnt that using function and implicit conversions in where clause is not optimal. To my surprise implicit conversion can be faster due to proper index usage.
I have a table called Records. Clustered index & primary key is on Id column (int) and non-clustered index on column Created (datetime). To avoid implicit conversion I created @dd variable.
declare @dd Datetime
set @dd = '2019-08-25'
--1st option
select * from Records where Created > @dd
--2nd option
select * from Records where Created > '2019-08-25'
--3rd option
select * from Records where Year(Created) = 2019 and MONTH(Created) = 8 and DAY(Created) = 25
Unfortunately 1st option uses Index scan (column Id). 2nd option uses index seek (column Created) and key lookup which is nice but I wonder why 1st option doesn't do the same. I've added 3rd option just to see the difference and it behaves as 1st option.
I've found query execution plan : missing index which leads to blog post about this behavior but it doesn't explain why it happens.
I can see there is a difference in estimated number of rows. When I set date to '2019-06-25'
, all three option are using similar plan with index scan.
So is it a rule of thumb to use implicit conversion when I can expect number of rows will be low? I am quite confused here.