I am having a tough time to understand why does LEFT JOIN
/ IS NULL
eliminate records which are there in one table and not in the other.
Here is an example
SELECT l.id, l.value
FROM t_left l
LEFT JOIN t_right r
ON r.value = l.value
WHERE r.value IS NULL
Why should r.value = NULL
eliminate records ? I am not understanding . I know I am missing something very basic but at present I cant figure out even that basic one. I would appreciate if someone explains it to me in detail .
I want a very basic explanation.
in your example, the result would be EVERY record from
t_left
, as well as every matching record fromt_right
where they both have the samevalue
. where there is no match,NULL
values are given instead of values fromt_right
.where r.value is null
simply eliminates the rows that did match, by detecting thosenull
values.essentially saying 'give me the rows from
t_left
that DONT match rows int_right
a
right join
performs the reverse order of theleft join
.Firstly a left join states that all records from the left table will be include, and only those from the right that match.
So lets say you have a
red
,blue
andgreen
sock in your drawer, and your friend only ared
,yellow
andblue
, a left join from your drawer to your friends would return all the socks from your drawer (red
,blue
andgreen
) and only matching ones from your friends (red
andblue
).Now the IS NULL part says that you want to see all socks from your drawer, where there are not matching pair partners in your friends drawer, so from all your socks the only one with a missing pair is the
green
sock.Left join
gives all records from left table. If the any key present in left table is missing in right table all right table column will be null, but all the left table values will be present.It is the basic difference between inner join and left / right join.
Thus when you do 'r.value = null` you get those records from left where there is no matching key in right table.
HTH.
LEFT JOIN takes the values on the left and tries to match the table on the left by the column specified on ON if it doesn't find a match then it interprets the right table's columns as NULL. hence only those that can't find a match on the right table will be selected by IS NULL operator
This could be explained with the following
Here
table1.id <-> table2.t1id
Now when we do a
left join
with the joining key and if the left table is table1 then it will get all the data from table1 and in non-matching record on table2 will be set to nullSee that table1.id = 3 does not have a value in table2 so its set as null When you apply the where condition it will do further filtering
it's super simple logic: