Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including specific records using a LEFT Join in SQL Server

I have two tables joined through a left join. I want to include all records in the Borrowers table but only records where Loan_Type = 'Auto' in the Loans table.

Here is all of the code in a working SQL Fiddle example:

SQLFiddle

These are my desired results

like image 438
user24190256 Avatar asked Aug 28 '26 21:08

user24190256


1 Answers

Instead of specifying the criteria in the WHERE clause, simply add the criteria to the join instead:

Rewrite this:

LEFT JOIN Loans l ON b.Loan_ID = l.Loan_ID
WHERE l.loan_type = 'Auto'

to this:

LEFT JOIN Loans l ON b.Loan_ID = l.Loan_ID AND l.loan_type = 'Auto'

WHERE filters the entire row from the resultset, whereas additional criteria in the joins will only filter that part of the join.

like image 158
Lasse V. Karlsen Avatar answered Aug 31 '26 15:08

Lasse V. Karlsen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!