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.
Quiz
0 / 1
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
Run
Generate
Tables
Execution Result