create table #t1 (id int)
create table #t2 (id int)
insert into #t1 values (1)
insert into #t1 values (2)
insert into #t1 values (3)
insert into #t2 values (1)
ins
This one is not correct:
select *
from
#t1 a left join #t2 b
on a.id = b.id and b.id is null
you want b.id
to be null AND, at the same time, to be b.id = a.id
. This can never be true, so the join will not succeed. You will get all rows from #t1 table but all null values for #t2.
This one is correct:
select *
from
#t1 a left join #t2 b
on a.id = b.id
where
b.id is null
you are using a LEFT JOIN, so your query will return all rows from #t1 and only the rows from #t2 where the join succeeds (and it will succeed when a.id = b.id
).
When the join doesn't succeed, b.id
will be set to null. Using WHERE b.id is null
you will get only the rows where the join won't succeed and you will get all values from #t1 which are not present in #t2.
You can try to run this query to see what's actually happening and to better understand the logic:
select *
from
#t1 a left join #t2 b
on a.id = b.id