Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
651 views
in Technique[技术] by (71.8m points)

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

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 the affect of CONVERT() function on INDEX see below:

Query1:
SELECT  *
FROM    myTable
WHERE   CONVERT(VARCHAR(10),DateFrom,23) >= '2011-01-01'

Query2:
SELECT  *
FROM    myTable
WHERE   DateFrom >= '2011-01-01 00:00:00.000'

I have checked & found no difference. But i was thinking that since the column is CONVERTED, so the index may not be used by the SQL Server, is it correct?

Please forgive me, if this is not a proper question.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...