Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between On or Where in LEFT JOIN?

Tags:

sql

left-join

What is the difference between the following pieces of SQL code:

select count(*)
from A
left join B
on a.id = b.id
where a.status = 2 and
b.id is NULL

and

select count(*)
from A
left join B
on a.id = b.id
and a.status =2
where b.id is NULL

? I read this : Semantic difference between join queries but I still don't know which one is better to use

I have spend the past hour reading this and grasping it all answers added value but I understood the code example together with "never encountered this" the best

like image 818
edelwater Avatar asked Nov 30 '22 15:11

edelwater


1 Answers

It is key to how LEFT joins are used, one will filter the result out, the other will merely fail the LEFT join, preserving data from the LEFT side of the JOIN.

(1) left join B on a.id = b.id where a.status = 2

Ignoring other filters, this says to LEFT JOIN against the table B, so, "try to join to table B using the condition a.id=b.id".
If you can't make a match, keep the records on the left table (i.e. A). Subsequent to that, on the remaining records, FILTER out (i.e. REMOVE) records that do not match a.status=2

(2) left join B on a.id = b.id and a.status =2

Ignoring other filters, this says to LEFT JOIN against the table B on 2 conditions, so, "try to join to table B on both conditions a.id = b.id and a.status =2". If you get no records from B given both conditions (even if one is unrelated to B), keep the record from A anyway.

like image 129
RichardTheKiwi Avatar answered Dec 02 '22 04:12

RichardTheKiwi