Skip to content
Advertisement

NULL values are excluded. Why?

This is about a bizarre behaviour I found in Microsoft Sql Server. Please correct me if I’m wrong.

SELECT COUNT(*) FROM TABLEA 
WHERE [Column1] IS NULL;

This returns 30018 rows.

CREATE VIEW VIEWB AS 
SELECT * FROM TABLEA AS t1 
WHERE t1.[Column1] NOT IN ('Cross/Up sell', 'Renegotiation', 'Renewal')  

If I check VIEWB, I don’t find NULL in Column1:

SELECT COUNT(*) FROM VIEWB 
WHERE [Column1] IS NULL;

This returns 0 rows.

Why? The query above excludes the 3 values, but it isn’t supposed to exclude NULL. Why does Ms Sql Server behave this way? Should I have expected this? How can I fix it?

Advertisement

Answer

This is actually a common mistake made with SQL Server in treating NULL as a value. By default, it’s treated as UNKNOWN, as documented here. So, in your view, you also need to include an OR t1.[Column1] IS NULL.

You can change this behavior by calling SET ANSI_NULLS OFF. It is not recommended to use this, however, as the feature is deprecated as pointed out by @Martin Smith.

This is not a SQL Server specific issue, however. It’s part of the ANSI SQL standard.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement