EXISTS() vs. SELECT COUNT(*) vs. EXISTS (SELECT *)
I was reading about optimizing EXISTS today and decided to try a couple of variations on this theme. In this example, all I want to know is does the ID exist in the table. I presumed the following would all work exactly the same:
Select count(*) From Jurisdiction WITH (NOLOCK) Where JID= 22
IF EXISTS(Select count(*) From Jurisdiction WITH (NOLOCK) Where JID= 22)
print 'exists 1'
IF EXISTS(Select * From Jurisdiction WITH (NOLOCK) Where JID= 22)
print 'exists 2'
IF EXISTS(Select 1 From Jurisdiction WITH (NOLOCK) Where JID= 22)
print 'exists 3'
To test, I turned on 'Include Actual Execution Plan' and ran.
To my surprise, the first, third and fourth queries each took 33% of the total but the second took zero. They all return the correct result - the first query returns '1', the rest print 'exists x'.
In the execution plan for the first, third and fourth queries, 100% of the time taken for each query is attributed to a clustered index seek. The second query only consists of a Constant scan.
Can you explain this? Is it using something in memory that it's not showing?