NULL handling in SQL Server lets you test, replace, and safely aggregate missing values so queries return the expected results.
NULL represents “unknown.” Arithmetic, concatenation, and comparisons that involve NULL return NULL, which can break filters, joins, and reports.
Use IS NULL
or IS NOT NULL
. Comparing with = NULL
never works because NULL is not a value.
column_name IS [NOT] NULL
in WHERE, JOIN, or CASE clauses.
Wrap the column in ISNULL()
or COALESCE()
. Both return the first non-NULL argument, letting you supply a fallback.
ISNULL()
is SQL Server–specific and returns the data type of its first argument; COALESCE()
is ANSI and evaluates multiple inputs. Prefer COALESCE()
for portability.
Yes. SUM()
, COUNT(col)
, AVG()
, MIN()
, and MAX()
automatically skip NULL rows, so no extra handling is required.
Use a CASE expression in ORDER BY
: ORDER BY CASE WHEN column IS NULL THEN 1 ELSE 0 END, column
.
Declare columns NOT NULL
whenever possible, document when NULL is meaningful, and use COALESCE()
in output layers instead of core tables.
Yes. COUNT(*) counts rows, not column values. Use COUNT(column) to skip NULLs.
No. NULL = NULL returns NULL. Use IS NULL on both columns or set ANSI_NULLS OFF (not recommended).
Performance is virtually identical for two arguments. COALESCE adds negligible overhead for more inputs.