SQL EXISTS performance
-
12-10-2019 - |
Question
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
Solution
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!
OTHER TIPS
Exists will stop after the first hit because then the expression evaluates to true, so the top(1)-part is unnecessary.
No, it won't.
SQL Server
uses TOP
in the plan to evaluate EXISTS
.
The statements generate identical query plans so there is no difference. The second example is easier to read in my opinion.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow