views:

322

answers:

5

I used to write my EXISTS checks like this:

IF EXISTS (SELECT * FROM TABLE WHERE Columns=@Filters)
BEGIN
   UPDATE TABLE SET Columns=VALUES WHERE Columns=@Filters
END

One of the DBA's in a previous life told me that when I do an EXISTS clause, use SELECT 1 instead of SELECT *

IF EXISTS (SELECT 1 FROM TABLE WHERE Columns=@Filters)
BEGIN
   UPDATE TABLE SET Columns=VALUES WHERE Columns=@Filters
END

Does this really make a difference?

A: 

Best way to know is to performance test both versions and check out the execution plan for both versions. Pick a table with lots of columns.

HLGEM
+1. No idea why this was down-voted. I always thought it was better to teach a man to fish, than to just give him a fish. How are people going to learn anything?
Ogre Psalm33
+1 Do it yourself advice is always welcome.
AlexKuznetsov
+3  A: 

Not any real difference but there might be a very small performance hit. As a rule of thumb you should not ask for more data than you need.

orjan
A: 

Personally I find it very, very hard to believe that they don't optimize to the same query plan. But the only way to know in your particular situation is to test it. If you do, please report back!

Larry Lustig
+15  A: 

No. This has been covered a bazillion times. SQL Server is smart and knows it is being used for an EXISTS, and returns NO DATA to the system.

Quoth Microsoft: http://technet.microsoft.com/en-us/library/ms189259.aspx?ppud=4

The select list of a subquery introduced by EXISTS almost always consists of an asterisk (*). There is no reason to list column names because you are just testing whether rows that meet the conditions specified in the subquery exist.

Also, don't believe me? Try running the following:

SELECT whatever
  FROM yourtable
 WHERE EXISTS( SELECT 1/0
                 FROM someothertable 
                WHERE a_valid_clause )

If it was actually doing something with the SELECT list, it would throw a div by zero error. It doesn't.

EDIT: Note, the SQL Standard actually talks about this.

ANSI SQL 1992 Standard, pg 191 http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt

     3) Case:

        a) If the <select list> "*" is simply contained in a <subquery> that is immediately contained in an <exists predicate>, then the <select list> is equivalent to a <value expression> that is an arbitrary <literal>.
Matt Rogish
+1 for 1/0 in EXISTS clause.
gbn
+4  A: 

There is no difference in SQL Server and it has never been a problem in SQL Server. The optimizer knows that they are the same. If you look at the execution plans, you will see that they are identical.

Cade Roux