Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 left join vs inner join

Author  Topic 

jrobin747
Starting Member

48 Posts

Posted - 2013-08-09 : 10:35:14
Why would I use a left join instead of a inner join when the columns entered within the SELECT command determine what is displayed from the query results?

James K
Master Smack Fu Yak Hacker

3873 Posts

Posted - 2013-08-09 : 11:07:08
quote:
Originally posted by jrobin747

Why would I use a left join instead of a inner join when the columns entered within the SELECT command determine what is displayed from the query results?

It's not the columns, it's the rows (well, sort of). Take a look at any basic SQL site. W3Schools for example ha s a pretty good explanation. http://www.w3schools.com/sql/sql_join_left.asp
Go to Top of Page

jrobin747
Starting Member

48 Posts

Posted - 2013-08-09 : 11:15:43
I loooked there before I posted my question. I sorta understand what joins do. But when I look at the results of my queries using inner joins I don't see why I need a left join.
Go to Top of Page

James K
Master Smack Fu Yak Hacker

3873 Posts

Posted - 2013-08-09 : 11:21:09
May be in your case you don't need LEFT JOINs. It depends on what your tables are and the kind of data you are looking for.

The classic example they cite is the case of customers and orders. You have a customers table which lists each customer - a customer id, name, address etc. Then, there is an orders table which has orderid, quantity, item etc. and the customer id.

If you do an inner join on the two tables, it will list all customers who have placed orders. But if you have customers who have not placed any orders at all (the window-shoppers), they will not be listed. If you do a LEFT JOIN, it will list all customers regardless of whether or not they have placed orders. For example, like this:
SELECT
c.CustomerName,
COUNT(DISTINCT o.OrderId) AS NumberOfOrders
FROM
Customers c
LEFT JOIN Orders o ON
o.CustomerId = c.CustomerId;
Go to Top of Page

jrobin747
Starting Member

48 Posts

Posted - 2013-08-09 : 13:00:33
GOT IT!
Go to Top of Page
   

- Advertisement -