Re: Left Join vs Right JOIN
- From: "tshad" <tfs@xxxxxxxxxxxxxx>
- Date: Mon, 15 Jun 2009 23:01:08 -0700
"Erland Sommarskog" <esquel@xxxxxxxxxxxxx> wrote in message
news:Xns9C2A742344FBBYazorman@xxxxxxxxxxxx
Hugo Kornelis (hugo@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx) writes:Now, there is an important question.
You usuallly should not need these types of join much. Most joins would
be the default "inner" join, written as
Yes and no. The need for outer joins are certainly very common. But I
sometimes come across queries that goes:
SELECT ..
FROM tbl
LEFT JOIN ...
LEFT JOIN ...
LEFT JOIN ...
LEFT JOIN ...
LEFT JOIN ...
Then it is a good guess that someone is using LEFT JOIN without thinking
of what it means, of whether that is the right thing.
The end result will be a result set with all CustomerDetails, along with
their Customer details (if he/she exists and is known), and the
Department details for that customer (if it exists and is known).
...
But as memorized before - in most shops, you'd expect the appropriate
FOREIGN KEY constraints on the cd.CustomerID and the d.Department
columns, and you'd further simplify this to
SELECT * -- Never use SELECT * in production code!!!
FROM CustomerDetail AS cd
INNER JOIN Customer AS c ON cd.CustomerID = c.CustomerID
INNER JOIN Department AS d ON c.DepartmentID = d.DepartmentID;
Here you make the important assumption that Customers.DepartmentID is
not nullable. We don't know the business, but it seems conceivable that
customers may not be associated with a department. In that case, there
is an important difference between an inner join and an outer join here.
If a field in an outer JOIN is not nullable, but because of the OUTER JOIN
would normally be a null if the criteria didn't match. What happens there?
Thanks,
Tom
--
Erland Sommarskog, SQL Server MVP, esquel@xxxxxxxxxxxxx
Links for SQL Server Books Online:
SQL 2008: http://msdn.microsoft.com/en-us/sqlserver/cc514207.aspx
SQL 2005: http://msdn.microsoft.com/en-us/sqlserver/bb895970.aspx
SQL 2000:
http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx
.
- Follow-Ups:
- Re: Left Join vs Right JOIN
- From: Plamen Ratchev
- Re: Left Join vs Right JOIN
- References:
- Left Join vs Right JOIN
- From: tshad
- Re: Left Join vs Right JOIN
- From: Hugo Kornelis
- Re: Left Join vs Right JOIN
- From: Erland Sommarskog
- Left Join vs Right JOIN
- Prev by Date: Re: Left Join vs Right JOIN
- Next by Date: need help on tackle a time series problem
- Previous by thread: Re: Left Join vs Right JOIN
- Next by thread: Re: Left Join vs Right JOIN
- Index(es):
Relevant Pages
|