Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subquery using Exists 1 or Exists *

I used to write my EXISTS checks like this:

IF EXISTS (SELECT * FROM TABLE WHERE Columns=@Filters) BEGIN    UPDATE TABLE SET ColumnsX=ValuesX WHERE 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 ColumnsX=ValuesX WHERE Columns=@Filters END 

Does this really make a difference?

like image 386
Raj More Avatar asked Oct 20 '09 21:10

Raj More


People also ask

What is the use of exists in subquery?

The EXISTS operator is used to test for the existence of any record in a subquery. The EXISTS operator returns TRUE if the subquery returns one or more records.

How do you use exists and not exists in SQL?

Use EXISTS to identify the existence of a relationship without regard for the quantity. For example, EXISTS returns true if the subquery returns any rows, and [NOT] EXISTS returns true if the subquery returns no rows. The EXISTS condition is considered to be met if the subquery returns at least one row.

Can I use exists in select statement?

The result of EXISTS is a boolean value True or False. It can be used in a SELECT, UPDATE, INSERT or DELETE statement.

Why do we use select 1 in SQL?

The statement 'select 1' from any table name means that it returns only 1. For example, If any table has 4 records then it will return 1 four times.


1 Answers

No, 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.

To check yourself, 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>.

like image 85
Matt Rogish Avatar answered Sep 19 '22 08:09

Matt Rogish