NULL Handling in SQL
In SQL, NULL represents a missing or unknown value. Unlike 0, an empty string, or false, it indicates the absence of data.
Understanding how to detect and manage NULL values is critical for writing accurate queries.
Checking for NULL
You cannot use = or != to compare against NULL. Instead, use:
IS NULL: checks if a value isNULLIS NOT NULL: checks if a value is notNULL
Find users without feedback
SELECT user_id
FROM course_feedback
WHERE feedback_text IS NULL;
Replacing NULLs: COALESCE and IFNULL
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 aNULLwith 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'.
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?
Ignoring NULLs can lead to unexpected filters, broken conditions, and inaccurate results.
Proper handling ensures your queries stay accurate and your reports reliable.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.