NULL as a concept seems so easy but it leads to so many problems for people. To put it as simply as possible, NULL does not equal anything. It does not “not equal” anything either. It can’t be compared to other values in any way. There was a recent post over at SQL Server Central where the user had a query problem that one of the great people over at SSC solved, handily. They also pointed out that the bit of code being used “WHERE nt.NullableString NOT LIKE ‘null%’” was also a problem. The user insisted that it was eliminating the NULL values. Well, yeah, sort of, it was, but not because it was actually applying a filter to the NULLs. Remember, a NULL does not equal or “not equal” anything and therefor when checking for the equality of something you won’t get NULL values.
Yeah, you’re thinking, so what’s the problem with the code then? This. It can lead to problems with your results. Here’s some sample code that illustrates the problem:
 CREATE TABLE #NullTest
(ID INT IDENTITY(1,1),NullableString NVARCHAR(50) NULL)
–I put the – next to the string NULL so you can see which one it is.
INSERT INTO #NullTest (
NullableString)
SELECTÂ ‘Some Value’
UNION
SELECT ‘NULL-‘
UNION
UNIONÂ
SELECTÂ ‘NULL values are not allowed’
UNIONÂ
SELECTÂ ‘NOT NULL’
–returns the five rows available
SELECTÂ * FROM #NullTest AS nt
–returns only two rows, although two other rows should be returned
SELECTÂ *
FROM #NullTest AS nt
WHEREÂ nt.NullableString NOT LIKE ‘null%’
–instead of returning three values, it only returns two, as it should
SELECTÂ *
FROM #NullTest AS nt
WHEREÂ nt.NullableString LIKE ‘NULL%’
— the real values that are not NULL, four of them
SELECTÂ *
FROM #NullTest AS nt
WHEREÂ NullableString IS NOT NULL
As you can see, the wrong number of rows are returned depending on how the query is used. There are four rows in the table that are NOT NULL (notice the syntax) but running the query the other way only returns two values. There are ongoing debates about the utility, meaning and purpose of NULLs. I’m not getting into it. If you’re using them, you need to understand what they are and what they are not.
i hate NULLs.
Nice post. I wasn’t in on the thread you mention, but I was in another one recently.
Unlike SQLBatman I don’t hate nulls.
Actually, I kind of like NULLs too. But you have to know what they are and how to work with them or they will chew on you quite severely.
Don’t get me started, Tom! 😉
[…] […]
Just a note,
NULL shouldn’t be considered as a value… it is a condition. It means ‘Unknown’ or ‘Not Yet Set’. This is a valid state when talking about data. We simply might not know, yet, what the column’s value should be. That’s fair. It’s also a condition that we can test for, or filter on.
We’ve all heard people talk about NULL ‘values’. I’ve done it myself. Ah Hah! When we treat NULLs as a condition, as they are intended by ANSI spec, then all of a sudden, syntax and design guidance become clearer. 🙂