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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With