SQL EXISTS 性能
我知道 SQL EXISTS
检查行是否存在,但是它会计算整个表达式吗?例如,像这样的事情会
IF EXISTS (SELECT TOP 1 1 FROM table WITH (NOLOCK))
BEGIN
...
END
比这样的事情更快:
IF EXISTS (SELECT 1 FROM table WITH (NOLOCK))
BEGIN
...
END
I understand that SQL EXISTS
checks for the existence of rows, however does it evaluate the entire expression? So for example, would something like this:
IF EXISTS (SELECT TOP 1 1 FROM table WITH (NOLOCK))
BEGIN
...
END
Be faster than something like this:
IF EXISTS (SELECT 1 FROM table WITH (NOLOCK))
BEGIN
...
END
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Exists 将在第一次命中后停止,因为表达式的计算结果为 true,因此 top(1) 部分是不必要的。
Exists will stop after the first hit because then the expression evaluates to true, so the top(1)-part is unnecessary.
这两个应该运行完全相同。 SQL Server考虑到
EXISTS
是一个短路操作,不会评估返回结果,只是检查是否有IS返回结果!Both those should run exactly the same. SQL Server takes into account that
EXISTS
is a short-circuited operation and doesn't evaluate the return result, just checks to see if there IS a return result!不,不会的。
SQL Server
在计划中使用TOP
来评估EXISTS
。No, it won't.
SQL Server
usesTOP
in the plan to evaluateEXISTS
.这些语句生成相同的查询计划,因此没有差异。我认为第二个例子更容易阅读。
The statements generate identical query plans so there is no difference. The second example is easier to read in my opinion.