1

I've a problem in using NULL with NOT in sub-query, the code is:

Create table #FirstTable(i int)
Create table #secondTable(i int)
insert into #FirstTable(i) values (1),(2),(3),(4),(5)
insert into #secondTable(i) values (2),(3),(null)

select * from #FirstTable where i not in (select i from secondTable);

The expected result would be 1,4,5 but it gives null, how can I get the expected value? The question is somehow similar to the referred question but specifically that question is including joints with different values

Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
Zia Ullah
  • 43
  • 9

3 Answers3

4

Using not exists is recommended approach rather than using not in

select * from #FirstTable f
where not exists(select 1 from #secondTable
                 where i = f.i)
Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
1

its because you have a null value in your 2nd table. filter it using isnull()

Create table #FirstTable(i int)
Create table #secondTable(i int)
insert into #FirstTable(i) values (1),(2),(3),(4),(5)
insert into #secondTable(i) values (2),(3),(null)

select * from #FirstTable where i not in (select isnull(i, 0) from #secondTable);

drop table #secondTable
drop table #FirstTable
Ed Bangga
  • 12,879
  • 4
  • 16
  • 30
1

You can add a where i is not null clause to your subquery to avoid this problem:

select * 
from #FirstTable 
where i not in (select i 
                from #secondTable 
                where i is not null);

Demo on dbfiddle

Nick
  • 138,499
  • 22
  • 57
  • 95