Welcome to Julian Kuiters Monday, May 21 2018 @ 07:48 AM AEST

Q&A: Why does WHERE LEN(columnname) = 0 skips NULL values?

  • Contributed by:
SQL Server 2000

Q: When I use the condition LEN(columnname) = 0, I don't get columns where columnname value is null. Why? Shouldn't LEN(NULL) = 0 ? Are my ANSI_NULLS or ANSI_DEFAULTS setting to blame?

A: No. LEN(NULL) will always return NULL. From SQL Server Books Online Null Values

A value of NULL indicates the value is unknown. A value of NULL is different from an empty or zero value. No two null values are equal. Comparisons between two null values, or between a NULL and any other value, return unknown because the value of each NULL is unknown.
...
When null values are present in data, logical and comparison operators can potentially return a third result of UNKNOWN instead of just TRUE or FALSE.

Ansi settings don't have any affect on this behaviour. You can check this with:

SET ANSI_DEFAULTS on
SELECT LEN(NULL), LEN('')
SET ANSI_DEFAULTS off
SELECT LEN(NULL), LEN('')
Both queries return the same results:
------------ ------------
NULL         0

(1 rows(s) affected)


------------ ------------
NULL         0

(1 rows(s) affected)

To correctly identify if your column contains a zero-width string or NULL, you can use either of these two sets of condtions:

WHERE LEN(columnname) = 0 OR columnname IS NULL
or
WHERE LEN(COALESCE(columnname,'')) = 0