Groups | Blog | Home
all groups > sql server programming > october 2004 >

sql server programming : AND Vs WHERE


Amit
10/5/2004 10:25:10 PM
Hi Sql Gurus,

Written below are two queries returning the same result
set.

SELECT A.Col1 FROM TableA AS A INNER JOIN TableB AS B ON
(A.Col1 = B.Col1) AND (B.Col2 = 5)

SELECT A.Col1 FROM TableA AS A INNER JOIN TableB AS B ON
(A.Col1 = B.Col1) WHERE (B.Col2 = 5)

Above two queries seem to be very simple, but in case of
complex queries joining three or more tables, i think its
better to restrict the number of records satisfying the
join condition by using AND clause immediately after the
join condition than to put a filter using WHERE clause at
the end.

To my understanding WHERE acts as a filter for the final
recordset available, and AND can be used to filter out the
unnecessary records before the WHERE clause comes in
picture.

I want to know which one of the two approaches is better
to use. Feel free to let me know if my question isn't
clear.

Thanks in advance,
David Gugick
10/6/2004 1:46:41 AM
[quoted text, click to view]

The following test queries return the same query plan. In both cases,
SQL Server scans sysobjects to get xtype = 'S' and then index seeks on
sysindexes to get the matches. I would argue that using WHERE is better
since the AND is not really a part of the join condition. It's a filter.

select a.name, b.name
from sysobjects a inner join sysindexes b
on a.id = b.id
where a.xtype = 'S'

select a.name, b.name
from sysobjects a inner join sysindexes b
on a.id = b.id
and a.xtype = 'S'



--
David Gugick
Imceda Software
www.imceda.com
David Portas
10/6/2004 7:03:11 AM
[quoted text, click to view]

That's the logical model of what happens but in reality the server is smart
enough to change the order of evaluation to make the most efficient
execution plan without changing the actual meaning of the query. In an INNER
JOIN, criteria appearing in either the ON or WHERE clauses are effectively
interchangeable and you will find that your two queries yield identical
execution plans.

[quoted text, click to view]

I don't think there is a single answer to that, it's a matter of programming
style and readability which comes down to personal preference or programming
standards in your organization. I tend to put the columns that are declared
as foreign keys in the JOIN clause and other criteria in the WHERE clause.

--
David Portas
SQL Server MVP
--

Toby Herring
10/6/2004 10:35:26 AM
If you were using a LEFT OUTER JOIN, you would get different results from
these two queries.

--
Toby Herring
MCDBA, MCSD, MCP+SB
Need a Second Life?
http://secondlife.com/ss/?u=03e0e5b303c234bf08e80ee40119a65e


[quoted text, click to view]

AddThis Social Bookmark Button