Available Tables

Next →

Handling NULL Values with COALESCE & NULLIF

In SQL, NULL represents missing or unknown data. Handling NULLs correctly is important to avoid unexpected results.

COALESCE

COALESCE(value1, value2, ...) returns the first non-NULL value from the list.

Example: To show a default message if a phone number is missing:

SELECT name, COALESCE(phone, 'No Phone') FROM students;

NULLIF

NULLIF(value1, value2) returns NULL if the two values are equal; otherwise, it returns the first value.

Example: To treat a zero as NULL:

SELECT NULLIF(score, 0) FROM students;

Using these functions helps you cleanly handle missing or special-case data in your queries.