What is the affect of CONVERT() on INDEX while searching?

前端 未结 1 1373
遇见更好的自我
遇见更好的自我 2020-12-19 01:55

I am using SQL Server 2008. I have a Non-Unique Non-clustered index on a DateTime Column \"DateFrom\". I am searching the table based on this column. I just wanted to know t

相关标签:
1条回答
  • 2020-12-19 02:53

    Generally, when you have a function on the left side of the comparison in a WHERE clause, the server will be unable to utilize the index on the referenced column.

    In your first example, there is no comparison to the DateFrom column directly. Instead, you are using a function on the column. When the server expands this, it must perform the function on each column value, and the resulting value is not indexed. Therefore, no index can be used to improve the query.

    Also, in your first example, you indicated that the DateFrom column is a datetime column. Yet, you're converting the column to a string and doing a string comparison. Hence, the server will not use your datetime index.

    In your second example, you are comparing the constant value with the date column directly, so the server may utilize the index. The server will convert the string constant on the right side of the comparison into a datetime value. However, it won't use the index in all cases. For example, if you have a very few number of rows, the server may decide not to use the index and just scan the few rows.

    Both queries may yield the same result set, but they are still very different.

    0 讨论(0)
提交回复
热议问题