473,805 Members | 2,172 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Adding conditions in the ON clause of a JOIN

Hi Faculties,
I have two queries which give me the same output.
-- Query 1
SELECT prod.name, cat.name
FROM products prod INNER JOIN categories cat
ON prod.category_i d = cat.id
WHERE cat.id = 1;

-- Query 2
SELECT prod.name, cat.name
FROM products prod INNER JOIN categories cat
ON prod.category_i d = cat.id AND cat.id = 1;
The first query uses the WHERE clause and the second one has all the
conditions in the ON clause. Is there anthing wrong with the second
approach in terms of performance? Please suggest.
Thanks in advance
Jackal
Feb 12 '08 #1
6 3110
On Feb 12, 12:10*pm, jackal_on_w...@ yahoo.com wrote:
Hi Faculties,
* * I have two queries which give me the same output.

* *-- Query 1
* *SELECT prod.name, cat.name
* *FROM products prod INNER JOIN categories cat
* * * *ON prod.category_i d = cat.id
* *WHERE cat.id = 1;

* -- Query 2
* *SELECT prod.name, cat.name
* *FROM products prod INNER JOIN categories cat
* * * *ON prod.category_i d = cat.id AND cat.id = 1;

* The first query uses the WHERE clause and the second one has all the
conditions in the ON clause. Is there anthing wrong with the second
approach in terms of performance? Please suggest.

Thanks in advance
Jackal

No issues if you use INNER JOINs
You may get different results if you use OUTER JOINs
Feb 12 '08 #2
Nothing wrong, it is more a question of preference. There is no logical
difference between ON and WHERE for inner joins, and has no effect on
performance. I normally prefer to write queries like the first example to
separate join conditions from filters.

There is only one situation where this may matter. SQL Server supports the
proprietary GROUP BY ALL. In that case the rows removed by the WHERE filter
are added back, so moving the filter between ON and WHERE will make a
difference.

Of course, this is valid for inner joins only, for outer joins it does
matter where you place filters and you will get different results.

HTH,

Plamen Ratchev
http://www.SQLStudio.com

Feb 12 '08 #3
Correcting your data element names a bit (vague dangling "id" and
"name"; the absurd "category_i d" that changes names from table to
table), you can also write:

SELECT P.product_name, C.foobar_catego ry
FROM Products AS P, VagueCategories AS C
WHERE P.foobar_catego ry = C.foobar_catego ry
AND C. foobar_category = 1;
Feb 12 '08 #4
(ja************ @yahoo.com) writes:
Hi Faculties,
I have two queries which give me the same output.
-- Query 1
SELECT prod.name, cat.name
FROM products prod INNER JOIN categories cat
ON prod.category_i d = cat.id
WHERE cat.id = 1;

-- Query 2
SELECT prod.name, cat.name
FROM products prod INNER JOIN categories cat
ON prod.category_i d = cat.id AND cat.id = 1;
The first query uses the WHERE clause and the second one has all the
conditions in the ON clause. Is there anthing wrong with the second
approach in terms of performance? Please suggest.
As long it's an inner join, it's only a matter of taste. I prefer to
put conditions on keys in the ON clause, and other conditions in the
WHERE clause. That is, if the condition is part of the join at all,
which it is not in this case.

If you have an outer join it's a completely different story, as you
could get different results. Common error:

SELECT ...
FROM a
LEFT JOIN b ON a.col1 = b.col1
WHERE b.type = 'X'

This query is effectively an inner join, because the WHERE clause
filters all rows where b.type are NULL. So here you need to put
b.type in the ON clause.

--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx
Feb 12 '08 #5
SELECT P.product_name, C.foobar_catego ry
FROM Products AS P, VagueCategories AS C
WHERE P.foobar_catego ry = C.foobar_catego ry
AND C. foobar_category = 1;
In SQL Server nobody uses that format any more in fact you'll confuse most
developers and leave yourself open to a cartesian product problem which was
common before we start using the ANSI 92 introduced INNER JOIN syntax.

Best practice definied in Books Online is to use INNER JOIN instead of the
prehistoric ANSI 89 style.

--
Tony Rogerson, SQL Server MVP
http://sqlblogcasts.com/blogs/tonyrogerson
[Ramblings from the field from a SQL consultant]
http://sqlserverfaq.com
[UK SQL User Community]

Feb 14 '08 #6
"Tony Rogerson" <to**********@t orver.netwrote in
news:fp******** ***********@new s.demon.co.uk:
>SELECT P.product_name, C.foobar_catego ry
FROM Products AS P, VagueCategories AS C
WHERE P.foobar_catego ry = C.foobar_catego ry
AND C. foobar_category = 1;

In SQL Server nobody uses that format any more in fact you'll confuse
most developers and leave yourself open to a cartesian product problem
which was common before we start using the ANSI 92 introduced INNER
JOIN syntax.

Best practice definied in Books Online is to use INNER JOIN instead of
the prehistoric ANSI 89 style.
Personally I get burned *by far* more for forgetting the WHERE clause and
having the conditions mingle with the JOIN operators (rather than the
preferred syntax error) than we ever had cartesian product problems back in
the days when ANSI joins didn't exist.

Cart product production is typically obvious. Weird combinations that can
arise from committing the above mistake are almost always non-trivial and
non-obvious.
Feb 23 '08 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
3080
by: 6thirty | last post by:
Hi, I've created a stocktaking database using Access XP. This is indexed by two fields - part number and shelf location. I am currently inputting all the data via a form. When I have entered a record such as: part number 202354-001 location C1-01
4
4497
by: John Siracusa | last post by:
I recently had a problem where a bunch of postgres backends were taking up huge amounts of CPU time. I found a bunch of log messages like this: NOTICE: adding missing FROM-clause entry for table "b" Which I eventually tracked to an improperly constructed query that reduced to something like this: select a1, a2 FROM a WHERE a1 = '...' AND b.b1 = '...';
1
3549
by: Martijn van Oosterhout | last post by:
Today I got the error: ERROR: FULL JOIN is only supported with mergejoinable join conditions Which is really annoying since a full join is exactly what I wanted. I guess the alternative is to do a left join and a right join and merge them? Is it just that no-one has come up with a way to code this efficiently? Maybe someone has a better way to express this. The problem is I have
3
4770
by: C G | last post by:
Dear All, I have a simple join query SELECT c1 FROM t1 INNER JOIN t2 ON t2.c2 = t1.c2 WHERE t3.c3= t2.c3; Which gives the expected result but I get the message NOTICE: adding missing FROM-clause entry for table "t3"
3
2269
by: lagj | last post by:
Using MySQL 5.0.15 I am no expert so maybe I am deeply misundertanding how this should work. I have a relatively complex quey with joins and a subquery (it is probably far from optimized, but that is another issue; right now I am more interested in correctness than speed). If I do not put a GROUP BY clause then the query returns a number of rows, as expected. If I add a GROUP BY clause, I get an empty set! My understanding of the...
5
2219
by: consonanza | last post by:
I am working on a report filter form. It has 2 combo boxes (cmboSelectSubject and cmboSelectCategory) to select criteria. Selecting an entry in combo 1 restricts the options available in combo 2. The row source for combo2 is: SELECT DISTINCT tblComplaintCategory.fldComplaintCategory, tblComplaintCategory.fldComplaintCategoryID, tblComplaintSubjects.fldComplaintSubjectID
69
8092
by: kabradley | last post by:
Alrighty Guys and Gals, I have another question that I hope you all can help me with. I have a report that uses a cross-tab query as its record source. This cross-tab query is getting all of its information from another query. That query, qryRpt, is pulling information from several different tables. One of these table is tblDistributions, a table that holds monthly distributions for a particular investment, and the second is tblDeduction, a...
1
2059
by: mtnbikur | last post by:
Lots of reading out there says you should only place “join criteria” in the join clause. That makes perfect sense. What about other search criteria? I’ve got other criteria, ie. cst_delete_flag = 0 that predecessors have put in the where clause and sometimes it’s programmed into the join clause. Ie. Select cst_id, cst_name, from co_customer left join mb_membership on mbr_cst_key = cst_key and mbr_delete_flag = 0 where...
12
25133
by: =?ISO-8859-1?Q?Ren=E9?= | last post by:
Hi, is there a rule of thumb what is better/faster/more performant in SQL Server 2005? a) SELECT * FROM A INNER JOIN B ON B.ID = A.ID AND B.Cond1 = 1 AND B.Cond2 = 2 b) SELECT * FROM A INNER JOIN B ON B.ID = A.ID WHERE B.Cond1 = 1 AND B.Cond2 = 2
0
9718
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10613
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10363
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10368
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9186
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6876
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5544
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5678
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3846
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.