[英]Date comparison BETWEEN vs < >
I have a question about the performance of the BETWEEN keyword vs. using the < and > operators to compare the upper and lower bound dates.我有一个关于 BETWEEN 关键字与使用 < 和 > 运算符比较上限和下限日期的性能的问题。
Example:例子:
WHERE EncDate BETWEEN '2010-04-30' AND GETDATE() - 1
WHERE EncDate > '2010-04-29' AND EncDate < GETDATE()
Both queries above should output the exact same number of rows, however, am I correct in assuming that BETWEEN keyword performs an inclusive (>= or <=) comparison behind the scenes which is not as performant as doing a < or > comparison from the second query?上面的两个查询都应该 output 完全相同的行数,但是,我是否正确假设 BETWEEN 关键字在幕后执行包容性(> = 或 <=)比较,其性能不如从第二个查询?
According to MSDN: BETWEEN根据 MSDN: BETWEEN
BETWEEN returns TRUE if the value of test_expression is greater than or equal to the value of begin_expression and less than or equal to the value of end_expression.
如果 test_expression 的值大于或等于 begin_expression 的值且小于或等于 end_expression 的值,则 BETWEEN 返回 TRUE。
So you are right, it is inclusive.所以你是对的,它是包容性的。
Regarding the first part of your question about performance, I believe BETWEEN
is just an alias for syntax of using >=
and <=
.关于性能问题的第一部分,我相信
BETWEEN
只是使用>=
和<=
语法的别名。 It is just to simplify and make query more readable.这只是为了简化并使查询更具可读性。
My assumption is based on following threads:我的假设基于以下线程:
These two are not the same!这两个不一样!
WHERE EncDate BETWEEN '2010-04-30' AND GETDATE() - 1
WHERE EncDate > '2010-04-29' AND EncDate < GETDATE()
They will produce the same result set if EncDate
is a date with no time component .如果
EncDate
是没有时间分量的日期,它们将产生相同的结果集。 Otherwise, they are different.否则,它们是不同的。
The general recommendation is to use:一般建议是使用:
WHERE EncDate >= '2010-04-30' AND
EncDate < CONVERT(DATE, GETDATE())
This has the same meaning regard of whether or not there is a time component.这对于是否存在时间分量具有相同的含义。
I am pretty sure that from an optimization perspective, these are exactly the same.我很确定从优化的角度来看,这些是完全相同的。 When working with databases, something as minor as comparing times is generally going to have no impact on performance -- the expensive operations are moving the data around.
在使用数据库时,比较时间这样的小事情通常不会对性能产生影响——昂贵的操作正在移动数据。
Aaron Bertrand has a very good discussion on using BETWEEN
with date/time data types, called What Do Between And The Devil Have In Common . Aaron Bertrand 对使用
BETWEEN
和日期/时间数据类型进行了很好的讨论,称为What Do Between And The Devil Have In Common 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.