Here is my code
SELECT ID, Name, Phone
FROM Table1
LEFT JOIN Table2 ON Table1.ID = Table2.ID
WHERE Table1.ID = 12 AND Table2.IsDefault = 1
<
Try this :
SELECT ID, Name, Phone
FROM Table1
LEFT JOIN Table2 ON Table1.ID = Table2.ID
WHERE Table1.ID = 12 AND isnull(Table2.IsDefault,1) = 1
You were almost there :-)
Use a subquery to filter the results of Table 2 before they're joined with Table 1:
SELECT ID, Name, Phone
FROM Table1
LEFT JOIN (SELECT * FROM Table2 WHERE IsDefault = 1) AS Table2 ON Table1.ID = Table2.ID
WHERE Table1.ID = 12
AND COALESCE(Table2.IsDefault,1) = 1
Reading the comments, it looks like your best solution is actually to move the condition to the join:
SELECT ID, Name, Phone
FROM Table1
LEFT JOIN Table2 ON Table1.ID = Table2.ID AND Table2.IsDefault = 1
WHERE Table1.ID = 12
Because it's an OUTER join, you'll still keep any Table1 information if the match fails, and given the statement that "Table2 will always return 1 entry" you're not risking filtering additional join results by moving the condition. You will get the same results as placing the condition in the WHERE clause.
The reason to move the conidtion to the ON clause is that the COALESCE()
, ISNULL()
, and OR
all cause problems for indexes. With the condition in the ON clause, we don't need any of those, and so should end up with a better execution plan.
SELECT ID, Name, Phone
FROM Table1
LEFT JOIN Table2
ON Table1.ID = Table2.ID AND Table2.IsDefault = 1
WHERE Table1.ID = 12
SELECT ID, Name, Phone FROM Table1
LEFT JOIN Table2 ON Table1.ID = Table2.ID
WHERE Table1.ID = 12
AND (Table2.IsDefault IS NULL OR Table2.IsDefault = 1);