SQL Server奇数性能在查询/不查询检查null值时结果
我必须修改一个查询,该查询检查给定日期是否位于某些视图结果集的 StartDate 和 EndDate 字段之间。 由于这些字段中没有包含空值的行,因此以下查询提供完全相同的结果。
SELECT *
FROM SomeView
WHERE (StartDate <= GETDATE())
AND (EndDate >= GETDATE())
SELECT *
FROM SomeView
WHERE ((StartDate IS NULL) OR (StartDate <= GETDATE()))
AND ((EndDate IS NULL) OR (EndDate >= GETDATE()))
我知道情况并不总是如此,这将取决于数据,但这不是我现在的问题。
如果我运行这些查询,第二个查询总是比第一个查询快 3-5 倍,尽管看起来它做了一些不必要的额外工作。 老实说,我试图查看执行计划,但由于此视图来自一个巨大的查询,其中包含来自其他表和视图的多个 JOIN,因此我无法确定 SQL Server 到底在检查这些日期时做了什么。 这怎么可能?难道不应该反过来吗?
I have to modify a query that is checking that a given date falls between the StartDate and EndDate fields of some View result set.
Since there is no row with null values in those fields, the following queries offer exactly the same results.
SELECT *
FROM SomeView
WHERE (StartDate <= GETDATE())
AND (EndDate >= GETDATE())
SELECT *
FROM SomeView
WHERE ((StartDate IS NULL) OR (StartDate <= GETDATE()))
AND ((EndDate IS NULL) OR (EndDate >= GETDATE()))
I know this is not always going to necessarily be the case, it will depend on the data, but that´s not my question now.
If I run those queries, the second one is always 3-5 times faster than the first one, even though it seems it´s doing some unneeded extra work.
To be honest, I have tried to see the execution plan, but since this View comes from a HUGE query with several JOINs from other tables and views, I cannot put my finger on what it is SQL Server really doing to check for these dates.
How is this possible? Shouldn´t it be the other way around?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果 StartDate 也可以为 null 那么
我猜这只是你的例子
StartDate
和EndDate
应为Datetime
数据类型EndDate 应为
'01/04/2022 0:00:00'
编辑:猜测
StartDate
和EndDate
在您的数据库中是可为空
。因此optmizer还会搜索Not Null行来过滤掉。如果
StartDate
和EndDate
为Not null
那么您的第一个查询会更快。如果你的第二个查询更快,那么我仍然会使用这个查询
if StartDate can be null also then
Guess this is just ur example,though
StartDate
andEndDate
should beDatetime
data typeEndDate should be
'01/04/2022 0:00:00'
Edited : Guess
StartDate
andEndDate
isnullable
in your database.So optmizer also search for Not Null row to filter out.If
StartDate
andEndDate
wasNot null
then your first query was faster.If you second query is faster then I will still use this query