NULL Handling
NULL Handling
Section titled βNULL HandlingβWhat it means
Section titled βWhat it meansβNULL represents βunknownβ or βabsentβ β itβs not zero, not an empty string, and critically, NULL = NULL evaluates to UNKNOWN (not TRUE), so you must test for it with IS NULL/IS NOT NULL rather than =. ISNULL(value, replacement) and COALESCE(value1, value2, ...) both substitute a fallback when a value is NULL β COALESCE is the ANSI-standard version and accepts more than two arguments.
Examples
Section titled βExamplesβSELECT * FROM Customers WHERE Email IS NULL;SELECT * FROM Customers WHERE Email IS NOT NULL;
-- WRONG way to test for NULL -- this never matches, even for NULL rows-- SELECT * FROM Customers WHERE Email = NULL;
SELECT Name, ISNULL(Phone, 'No phone on file') AS PhoneDisplay FROM Customers;
-- COALESCE returns the first non-NULL value from the listSELECT Name, COALESCE(MobilePhone, HomePhone, WorkPhone, 'No phone') AS BestContactFROM Customers;
-- NULL propagates through arithmetic: any calculation involving NULL is NULLSELECT 5 + NULL; -- returns NULL, not 5Common mistake
Section titled βCommon mistakeβTesting for NULL with = NULL instead of IS NULL β this is a very common trap, since it looks correct but always evaluates to UNKNOWN (treated as false), silently returning zero rows even when NULL values exist.
-- Returns NO rows, even if some customers genuinely have a NULL EmailSELECT * FROM Customers WHERE Email = NULL;
-- CorrectSELECT * FROM Customers WHERE Email IS NULL;Quick practice
Section titled βQuick practiceβ-
Why does
WHERE Email = NULLnever match any rows, even ones whereEmailis actually NULL?Answer
In SQL, comparing anything to NULL with=evaluates toUNKNOWN, notTRUEβ you must useIS NULLto correctly test for NULL values. -
Whatβs the difference between
ISNULL()andCOALESCE()?Answer
Functionally similar for two arguments, butCOALESCE()is ANSI-standard SQL and accepts any number of arguments, returning the first non-NULL one;ISNULL()is SQL Server-specific and takes exactly two. -
What does
5 + NULLevaluate to?Answer
NULLβ NULL propagates through arithmetic operations rather than being treated as zero.