Null Handling

NULL means missing or unknown value. It is not equal to 0, an empty string, or false.

Basic NULL Checks

WHERE column IS NULL
WHERE column IS NOT NULL

Use IS NULL, not = NULL.

IFNULL

IFNULL(x, y) returns y if x is NULL; otherwise it returns x.

SELECT product_name, IFNULL(discount, 0) AS discount
FROM products;

ISNULL

In MySQL, ISNULL(var) returns 1 if the value is NULL, otherwise 0.

ISNULL(var)

NULLIF

NULLIF(arg1, arg2) returns NULL if the two arguments are equal. Otherwise it returns arg1.

It is often used to avoid division by zero:

SELECT amount / NULLIF(quantity, 0) AS price_per_unit;

COALESCE

COALESCE returns the first non-NULL argument.

SELECT COALESCE(phone, email, 'No contact') AS contact_method
FROM customers;

NULL Sorting

Make NULL values come last when sorting ascending:

-- MySQL
ORDER BY column IS NULL, column ASC
 
-- PostgreSQL
ORDER BY column NULLS LAST

Relation To Filtering

SQL Filtering And Aggregation needs explicit NULL handling because conditions can silently remove missing values.