Handling NULLs: IS NULL, COALESCE(), IFNULL()

Imagine This

You’re collecting a list of student grades, but some students haven’t submitted their homework yet. So their grade is just blank — not 0, not absent, just unknown.

In databases, that “blank” is called NULL — it means “no value”.

SQL gives us tools to check for NULLs or even replace them with default values when needed.

Your Table: grades

studentsubjectscore
AliceMath85
BobMathNULL
CharlieMath92
DianaMathNULL

1. Checking for NULL: IS NULL

SELECT student
FROM grades
WHERE score IS NULL;

Output:

student
Bob
Diana

This query asks: “Which students have no score recorded?” You can’t use = NULL — you have to use IS NULL.

2. Replacing NULLs: COALESCE()

SELECT student, COALESCE(score, 0) AS final_score
FROM grades;

Output:

studentfinal_score
Alice85
Bob0
Charlie92
Diana0

COALESCE(score, 0) checks if score is NULL. If it is, it replaces it with 0. Otherwise, it shows the actual score.

3. Another Option: IFNULL() (MySQL, SQLite)

SELECT student, IFNULL(score, 0) AS final_score
FROM grades;

This works the same way as COALESCE(), but it’s specific to MySQL and SQLite. It only supports two arguments.

Summary

FunctionUse Case
IS NULLCheck if a value is missing
COALESCE()Replace NULL with the first non-null value
IFNULL()Replace NULL with a value (MySQL/SQLite)

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top