Nelrick Rodrigues
COMPARING NULL VALUES IN SQL SERVER
The examples below describe how to compare or evaluate fields having NULL values in SQL Server.
First, let us see an example what happens if NULL values are compared. For this, a simple CASE statement
is executed as shown below.
The Flag value in the above example is returned as a 0 which is incorrect, since if the value is NULL, a
value of 1 should be returned. This is a very simple test that proves that two NULL values cannot be
compared using the = operator.
Using the IS NULL clause:
The IS NULL clause is the simplest way to check if any column is having a NULL value. As seen above, the
Flag value of 1 is returned which is as expected.
Using the ISNULL function:
Nelrick Rodrigues
The ISNULL function is useful if you need to join between two columns that may contain NULL values. So,
even if you need the joins to happen between the NULL values for the two columns, you can default the
NULL value to a constant (0 in the above example) using the ISNULL function.
Using the COALESCE function:
The ISNULL function allows to specify only a single value that would be used in case the field contains a
NULL value. The COALESCE function, on the other hand allows you to specify multiple fields that will be
checked from left to right if they contain a NULL value. If the first field value is NULL, it will keep moving
to the next field on the right till it gets a field with a non-NULL value.