Skip to main content
Practice

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 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

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?

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.