Skip to main content
Practice

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 is NULL
  • IS NOT NULL: checks if a value is not NULL

Find users without feedback
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 a NULL 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_idcourse_namefeedback_text
1SQL BasicsGreat course!
2SQL BasicsNULL
3SQL BasicsNULL

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_idcourse_namecomment
1SQL BasicsGreat course!
2SQL BasicsNo comment
3SQL BasicsNo comment

When do I need to handle NULLs?

Failing to handle NULLs can cause unexpected filtering results, broken CASE logic, and incorrect calculations or reports.

Handling NULLs ensures your data remains clean and meaningful.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.