2

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 
2
  • 2
    How about you execute and look at the Query Execution Plan Commented Jan 19, 2011 at 14:44
  • 1
    Yep, I just did and they are exactly the same. Commented Jan 19, 2011 at 21:53

4 Answers 4

4

Exists will stop after the first hit because then the expression evaluates to true, so the top(1)-part is unnecessary.

Sign up to request clarification or add additional context in comments.

Comments

3

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!

Comments

2

No, it won't.

SQL Server uses TOP in the plan to evaluate EXISTS.

Comments

2

The statements generate identical query plans so there is no difference. The second example is easier to read in my opinion.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.