2

I have 2 table A and B

table A

subgroup    |   maingroup   |   
------------------------------------------  
NULL        |   A       |   
NULL        |   A       |   
Top     |   B       |   
Top     |   B       |   

table B

subgroup
---------------     
top             
NULL    

I am running this query.

select * from a
join b
on a.subgroup=b.subgroup
group by a.subgroup,a.maingroup,b.subgroup

I am getting this output

subgroup    |   maingroup   |   subgroup    
------------------------------------------------------- 
Top     |   B       |   Top 

My concern is why NULL is not matching and giving me output like NULL A Null.

I am using MSSQL

jpmc26
  • 28,463
  • 14
  • 94
  • 146
Red Devil
  • 2,343
  • 2
  • 21
  • 41
  • 1
    Possible duplicate of [Is there any difference between IS NULL and =NULL](http://stackoverflow.com/questions/3777230/is-there-any-difference-between-is-null-and-null) – jpmc26 Jun 29 '16 at 03:54

3 Answers3

6

If you want the NULL values from your two tables to match up during the join, one option is to add an explicit condition in your ON clause:

SELECT *
FROM a INNER JOIN b
    ON a.subgroup = b.subgroup OR (a.subgroup IS NULL AND b.subgroup IS NULL)
GROUP BY a.subgroup, a.maingroup, b.subgroup

The need for the explicit join condition a.subgroup IS NULL AND b.subgroup IS NULL is that comparing two NULL values for equality itself returns NULL, which is another way of saying the result is unknown.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

If you want the NULL values from your two tables to match up during the join, you can use the IsNull function.

SELECT *
FROM a INNER JOIN b
    ON IsNull(a.subgroup,'') = IsNull(b.subgroup,'')
GROUP BY a.subgroup, a.maingroup, b.subgroup
Fred Sobotka
  • 5,252
  • 22
  • 32
0

Simple try with ISNULL function as

SELECT *   FROM a INNER JOIN b

ON ISNULL(a.subgroup,'') = ISNULL(b.subgroup,'')

GROUP BY a.subgroup, a.maingroup, b.subgroup
Nazir Ullah
  • 610
  • 5
  • 13
  • Assuming that you want to treat `NULL`s as `0`s or that `0` (or a different value that should be substituted) can act as a sentinel value that doesn't exist in the actual data. – Damien_The_Unbeliever Jun 29 '16 at 06:15