Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server LEFT JOIN and WHERE clause

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#

like image 784
Felipe Miosso Avatar asked Oct 28 '13 13:10

Felipe Miosso


People also ask

Can I use WHERE in left join?

Left join is applied to the tables Course and Student and the table below is the result set. The left table and its corresponding matching rows on the right table are displayed. If a user wants to display the rows only in the left table, where clause can be used in the query.

Can we use join and WHERE clause together?

To use the WHERE clause to perform the same join as you perform using the INNER JOIN syntax, enter both the join condition and the additional selection condition in the WHERE clause. The tables to be joined are listed in the FROM clause, separated by commas. This query returns the same output as the previous example.

What is the difference between left join with WHERE clause and left join with WHERE clause?

When you use a Left Outer join without an On or Where clause, there is no difference between the On and Where clause. Both produce the same result as in the following. First we see the result of the left join using neither an On nor a Where clause.


1 Answers

SELECT ID, Name, Phone 
FROM Table1 
LEFT JOIN Table2 
ON Table1.ID = Table2.ID AND Table2.IsDefault = 1
WHERE Table1.ID = 12
like image 194
t-clausen.dk Avatar answered Oct 23 '22 21:10

t-clausen.dk