I have a SQL query whose execution plan depends on the DateTime parameters that I provide. I understand that if I have a condition like:
WHERE Date > '2012-02-28' AND Date < '2012-01-01'
then the execution plan will just be the evaluation of a constant, because no result will be returned. But in other cases I get different execution plans that don’t make any sense to me. For example with condition:
WHERE Date >= '2012-02-01 00:00:00' AND Date <= '2012-02-02 22:00:00'
the query uses an index that I added and it is optimized. But if I change the condition to:
WHERE Date >= '2012-02-27 00:00:00' AND Date <= '2012-02-27 22:00:00'
it doesn’t use the index anymore.
I rebuilt all the indexes on this table before running the queries. I can’t find any logic in this. So my question is: how can DateTime parameters affect which execution plan is chosen for a query?
EDIT: Apparently the reason was that I had an additional index on Date only that confused the SQL Server. After removing that index everything worked as expected. But thank you for the ideas. I didn’t offer enough details for you to figure that out. Too many indexes are never good!
SQL Server keeps statistics on the table content and builds the query plan based on those statistics.
For example. When I have a table with 1 million records where 900.000 records are between 2012-02-27 and 2012-02-28 the query governor will do a table scan to read the data. If only 10% of the data has dates between those 2 values it will prefer to use the index you created.
One issue with the statistics model is that of “outdated statistics”. SQL Server will do an “auto update statistics” whenever more than a certain percentage of the table or more than 500 records + (20% of the data cardinality) have been altered. (see this article).
So if your statistics are out of date, SQL Server may well come up with incorrect query plans.