Joining Tables That Contain NULL Values

As you can see we have two tables, with the same values.

Joining on these tables is no problem at all.  Simple, right?  Well, take a look at what happens when we try to join on the column containing the NULL values.

The results are the following:

As you can see, we are missing a row.  The row containing the NULL values did not get picked up by our join. We should have all three rows in the result set.  The join statement does not deal with NULL values well when joining.  So we can use ISNULL to replace the NULL values with something else.  How about if we just replace the NULLs with an empty space.

The results are even worse when running this query.

Since we are only joining on Column2 anytime there is an NULL or empty space the two tables are joined.  This is why we get the second and fourth rows back.  The reason we get NULL back in the table is because we are returning the actual table values, NULL in those cases, and only replacing the NULL with a blank space for the join; we are not actually altering the table at all. The solution is to replace the NULL values with something that is not going to appear anywhere else in our table.

Finally!  The results we want.

The long and the short of it is, if you want to do joins on columns that can contain NULL values, be ready for some suprising results.  Make sure you always build in some logic that will prevent the crazy results like those seen above.  Happy joining.

Bradley Schacht

Bradley Schacht is a Data Platform Solution Architect on the state and local government team with Microsoft based in Jacksonville, FL. He has co-authored 3 SQL Server books including "SQL Server 2014 Professional Administration". As a former consultant and trainer, he uses his experience on many parts of the Microsoft BI and data platform to help customers deliver the best possible solutions. Bradley frequently presents at community events around the country. He is a contributor to sites such as SQLServerCentral.com and an active member of the Jacksonville SQL Server User Group (JSSUG).

You may also like...

Leave a Reply