开发者

SQL Server 2008 datetime type time comparison

开发者 https://www.devze.com 2023-04-13 07:54 出处:网络
Is the following query the most inefficient way to filter by only the time part datetime field in SQL Server 2008?

Is the following query the most inefficient way to filter by only the time part datetime field in SQL Server 2008?

SELECT *
FROM mytable
WHERE CAST([DATEEND]开发者_如何学Python as TIME ) > "5:00PM";

Are there any major caveats or performance issues in doing the type casting in the where statement?

Are there any better alternatives or best practices?


The main issue with this query is that it is unsargable. Even if the DATEEND column is indexed then the index cannot be used.

The only way of making this query index friendly would be to have an computed column with definition CAST([DATEEND] as TIME) and then index it.

Even if you were to do that you may well find that the index isn't used though as it will depend how selective the query is. As your query uses * the index will need to do key lookups to retrieve the non covered columns. The exact selectivity at which the index would be used depends on the "Tipping Point"

You could also make the index covering by INCLUDE-ing the missing columns but as you are selecting all columns in the table that will make the index very wide which means more logical reads to scan it as well as more expensive to maintain for data modification statements.

0

精彩评论

暂无评论...
验证码 换一张
取 消