Here's the situation I'm dealing with. The original query I had was:
SELECT c.CustID, a.City, a.Country FROM Customers AS c
LEFT OUTER JOIN Addresses AS a ON c.CustID = a.CustID
WHERE c.LastName = 'Jones'
So I'd like to show all customers with last name Jones, even ones without any address entries, and show associated addresses for them. But what if I want a WHERE clause on the addresses but still show all customers? For example if I do this:
SELECT c.CustID, a.City, a.Country FROM Customers AS c
LEFT OUTER JOIN Addresses AS a ON c.CustID = a.CustID
WHERE c.LastName = 'Jones' AND a.Country = 'United States'
I lose any customers that are not in the United States. But that's not what I want. I want all customers with last name 'Jones', and only omit addresses that are not in the United States. This is the solution I came up with:
SELECT c.CustID, a.City, a.Country FROM Customers AS c
LEFT OUTER JOIN
(SELECT City, Country FROM Addresses
WHERE Country = 'United States') AS a
ON c.CustID = a.CustID
WHERE c.LastName = 'Jones'
In this case, I still get all customers with the last name Jones, but don't see addresses that are outside the US, which is what I wanted.
Here's my issue: In the third query, I'm assuming that SQL Server fetches all US addresses and then does the join with the Customers table, meaning many non-Jones addresses were fetched unnecessarily. In the second query, I'm wondering if SQL Server only fetches US addresses where LastName = 'Jones' in the first place, which I would think would make the query far faster. So is there a performance increase to the 2nd query over the 3rd? Also, whatever answer you give, if could you also comment on any differences when dealing inner joins instead (if there are any) that'd be great.
Thanks!