= (Equals) (Transact-SQL)
Compares the equality of two expressions (a comparison operator).
When you compare two NULL expressions, the result depends on the ANSI_NULLS setting:
-
If ANSI_NULLS is set to ON, the result is NULL, following the ANSI convention that a NULL (or unknown) value is not equal to another NULL or unknown value.
-
If ANSI_NULLS is set to OFF, the result of NULL compared to NULL is TRUE.
Comparing NULL to a non-NULL value always results in FALSE.
Comparing strings with trailing spaces gives unexpected results
When using the = operator to compare varChar strings of different lengths, SQL Server will pad the shorter string with spaces before performing the comparison which can give unexpected results for the following statements.
For example, all three of the following will output 'equal' despite the varying number of trailing spaces in the operands:
For more information on see MS KB 316626 "INF: How SQL Server Compares Strings with Trailing Spaces"
http://support.microsoft.com/default.aspx/kb/316626
For example, all three of the following will output 'equal' despite the varying number of trailing spaces in the operands:
if '' = ' ' print 'equal' else print 'not equal'
if ' ' = ' ' print 'equal' else print 'not equal'
if 'abc' = 'abc ' print 'equal' else print 'not equal'
For more information on see MS KB 316626 "INF: How SQL Server Compares Strings with Trailing Spaces"
http://support.microsoft.com/default.aspx/kb/316626
- 9/9/2009
- JohnFx
Comparing NULL to non-NULL results in Unknown
The text states "Comparing NULL to a non-NULL value always results in FALSE." This is incorrect. Per ANSI/ISO SQL standards, comparing NULL to a non-NULL value should always result in neither TRUE nor FALSE, but the third logical value: UNKNOWN.
If comparing NULL to a non-NULL value always resulted in FALSE, then the following would be false:
(10 = NULL)
Logically the following would have to be the "opposite" of FALSE (that is, it would have to be TRUE):
NOT (10 = NULL)
You put these in IF statements to quickly determine that neither returns TRUE nor FALSE.
If comparing NULL to a non-NULL value always resulted in FALSE, then the following would be false:
(10 = NULL)
Logically the following would have to be the "opposite" of FALSE (that is, it would have to be TRUE):
NOT (10 = NULL)
You put these in IF statements to quickly determine that neither returns TRUE nor FALSE.
- 4/4/2009
- Mike C_1
