SQL Server LEFT JOIN and WHERE clause

Felipe Miosso picture Felipe Miosso · Oct 28, 2013 · Viewed 68.3k times · Source

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

The problem happens when Table2 is null, so, the query returns nothing.

How do I leave the last part of the query AND Table2.IsDefault = 1 optional?

I've tried to short circuit the query using OR but I've found out that it works different than C#

Answer

t-clausen.dk picture t-clausen.dk · Oct 28, 2013
SELECT ID, Name, Phone 
FROM Table1 
LEFT JOIN Table2 
ON Table1.ID = Table2.ID AND Table2.IsDefault = 1
WHERE Table1.ID = 12