NULL Handling in SQL
In SQL, NULL
represents a missing or unknown value. It's not the same as 0
, an empty string, or false
. It means “no data.”
Understanding how to detect and manage NULL
values is critical for writing accurate queries.
Checking for NULL
You can't use =
or !=
to compare against NULL
. Instead, use:
IS NULL
: checks if a value isNULL
IS NOT NULL
: checks if a value is notNULL
SELECT user_id FROM course_feedback WHERE feedback_text IS NULL;
Replacing NULLs: COALESCE
and IFNULL
You can use COALESCE
and IFNULL
to replace NULL
values with a fallback value.
COALESCE(value1, value2, ...)
returns the first non-null value.IFNULL(value, fallback)
replaces aNULL
with the fallback (only in some SQL engines like MySQL or SQLite).
Example: Replace missing feedback with 'No comment'
Assume we have the following table:
user_id | course_name | feedback_text |
---|---|---|
1 | SQL Basics | Great course! |
2 | SQL Basics | NULL |
3 | SQL Basics | NULL |
We want to replace missing feedback with 'No comment'.
SELECT user_id, course_name, COALESCE(feedback_text, 'No comment') AS comment FROM course_feedback;
The query returns the following:
Result:
user_id | course_name | comment |
---|---|---|
1 | SQL Basics | Great course! |
2 | SQL Basics | No comment |
3 | SQL Basics | No comment |
When do I need to handle NULLs?
Failing to handle NULL
s can cause unexpected filtering results, broken CASE
logic, and incorrect calculations or reports.
Handling NULL
s ensures your data remains clean and meaningful.
Which SQL function returns the first non-NULL value from a list of expressions?
IS NULL
COALESCE
IFNULL
NULLIF
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Tables
Execution Result