My SSMS code is as follows:
Select top(50)
From FilteredContact
Where statuscode = 1
and emailaddress1 != 'NULL'
and telephone1 != 'NULL'
and address1_line1 != 'NULL'
I realize that ideally, the last three lines are to be formatted as follows:
and emailaddress1 IS NOT NULL
and telephone1 IS NOT NULL
and address1_line1 IS NOT NULL
However, my original code actually worked completely fine. Why is that? I thought NULL was an unknown value, not a string value equal to 'NULL'
If anyone knows, an explanation would be greatly appreciated! Thanks.
emailaddress1 != 'NULL'
comparesemailaddress1
and the string'NULL'
. Since the field is almost certainly a string, the type matches well enough. And since no one's going to have an email address of'NULL'
, the comparison won't eliminate valid rows (which have non-null, but also non-'NULL'
, values).Where things get a bit less intuitive is when the field's value is actually
NULL
. In standard SQL, the result of just about any comparison with a null value isUNKNOWN
(which is generally treated the same asNULL
). Since the DBMS only returns rows where the condition is true, it won't return that row.So the comparison works unless the string
'NULL'
would otherwise be valid in that field.This doesn't involve
ANSI_NULL
(I don't think). You are trying to match a string in your where clause. When you look for!='NULL'
, you are asking SSMS to return anything that is not the string "NULL". SinceNULL
is an unknown and all comparisons to it will beNULL
, it will only return other valid strings.I'm guessing
https://docs.microsoft.com/en-us/sql/t-sql/statements/set-ansi-nulls-transact-sql?view=sql-server-2017
Or as others have suggested
NULL
is being stored as string.Worked by accident. If for example
emailaddress1 ='NULL'
(a string value consisting of four characters: N U L L), then the condition evaluates to FALSE, and is incorrect. Since the email address is unlikely to beNULL
, then yes - it worked perfectly :)See this answer for a long explanation: NOT IN selection with NULL values
In short:
In your condition, say
and telephone1 != 'NULL'
, iftelephone
is NULL, then the whole conditions evaluates to NULL, which is treated asfalse
condition in the WHERE clause.