Reading history

SQL NULL Values: IS NULL, COALESCE and NULLIF

4 min read 0 views

Understand NULL in SQL: why = NULL fails, three-valued logic, IS NULL, COALESCE, NULLIF, and how COUNT, AVG and other aggregates treat missing values.

NULL is SQL’s marker for a missing or unknown value: a student who has not been graded yet, a customer with no phone number, an order whose amount is not known. It is not zero and not an empty string, and it behaves differently from every other value. Most surprising query results in SQL can be traced back to NULL, so this lesson shows exactly how it works and how to handle it with IS NULL, COALESCE and NULLIF.

In this lesson you will learn

  • What NULL means and why = NULL never works
  • Testing with IS NULL and IS NOT NULL
  • How NULL behaves in arithmetic and comparisons
  • Replacing NULL with COALESCE
  • How aggregate functions treat NULL, and NULLIF

The examples use the same students table as earlier lessons; Nadia’s CGPA is NULL because she has not been graded yet.

Testing for NULL

-- Rows where a value is missing
SELECT id, name, cgpa FROM students WHERE cgpa IS NULL;

-- NULL is not equal to anything, not even NULL
SELECT COUNT(*) AS equals_null FROM students WHERE cgpa = NULL;

SELECT NULL = NULL AS null_equals_null,
       NULL + 5 AS null_plus_5,
       NULL IS NULL AS is_null_check;

Output

+----+-------+------+
| id | name  | cgpa |
+----+-------+------+
| 8  | Nadia | NULL |
+----+-------+------+
(1 row)

+-------------+
| equals_null |
+-------------+
| 0           |
+-------------+
(1 row)

+------------------+-------------+---------------+
| null_equals_null | null_plus_5 | is_null_check |
+------------------+-------------+---------------+
| NULL             | NULL        | 1             |
+------------------+-------------+---------------+
(1 row)
  • Use IS NULL and IS NOT NULL to find missing values.
  • cgpa = NULL matches no rows, not even Nadia’s. Comparing anything with NULL gives the result unknown (shown as NULL), and WHERE keeps only rows where the condition is true.
  • Arithmetic with NULL gives NULL: if one part of a calculation is unknown, the answer is unknown too.
  • SQL uses three-valued logic: TRUE, FALSE and UNKNOWN. NOT (unknown) is still unknown, which is why WHERE cgpa <> 3.5 also skips the NULL row.

COALESCE, Aggregates and NULLIF

-- COALESCE returns the first value that is not NULL
SELECT name, COALESCE(cgpa, 0) AS cgpa_or_zero,
       COALESCE(CAST(cgpa AS TEXT), 'not graded') AS cgpa_label
FROM students
WHERE dept = 'CSE';

-- Aggregates skip NULLs: AVG over 7 values, not 8
SELECT COUNT(*) AS rows_total, COUNT(cgpa) AS rows_with_cgpa,
       ROUND(AVG(cgpa), 2) AS avg_ignoring_null,
       ROUND(AVG(COALESCE(cgpa, 0)), 2) AS avg_counting_null_as_0
FROM students;

-- NULLIF turns a chosen value into NULL (avoids division by zero)
SELECT 100 / NULLIF(0, 0) AS safe_division;

Output

+--------+--------------+------------+
| name   | cgpa_or_zero | cgpa_label |
+--------+--------------+------------+
| Nusrat | 3.82         | 3.82       |
| Tania  | 3.95         | 3.95       |
| Mitu   | 3.67         | 3.67       |
| Nadia  | 0            | not graded |
+--------+--------------+------------+
(4 rows)

+------------+----------------+-------------------+------------------------+
| rows_total | rows_with_cgpa | avg_ignoring_null | avg_counting_null_as_0 |
+------------+----------------+-------------------+------------------------+
| 8          | 7              | 3.5               | 3.06                   |
+------------+----------------+-------------------+------------------------+
(1 row)

+---------------+
| safe_division |
+---------------+
| NULL          |
+---------------+
(1 row)
  • COALESCE(a, b, ...) returns the first argument that is not NULL. It is the standard way to show a default, such as 0 or “not graded”. (MySQL’s IFNULL and SQL Server’s ISNULL are two-argument versions.)
  • COUNT(*) counts rows; COUNT(column) counts only non-NULL values: 8 versus 7 here.
  • AVG, SUM, MIN and MAX also ignore NULLs, so the average is over 7 students. Replacing NULL with 0 first gives a very different, and here misleading, average of 3.06. Decide deliberately which one your report needs.
  • NULLIF(a, b) returns NULL when a equals b. Dividing by NULLIF(x, 0) turns a division-by-zero error into a NULL result.

NULL Rules at a Glance

ExpressionResult
NULL = NULLNULL (unknown)
NULL IS NULLTRUE
NULL + 5, 'a' || NULLNULL
TRUE AND NULLNULL
TRUE OR NULLTRUE
x IN (1, NULL) when x = 2NULL, so the row is not returned

In ORDER BY, SQLite and MySQL put NULLs first in ascending order, while PostgreSQL and Oracle put them last. Add NULLS FIRST or NULLS LAST where supported to be explicit.

Common Mistakes

  1. Writing = NULL instead of IS NULL.
  2. Using NOT IN with a subquery that can return NULL: one NULL makes the whole condition unknown and returns no rows. Use NOT EXISTS instead.
  3. Assuming COUNT(column) counts every row.
  4. Storing “unknown” as 0 or ”, which mixes up “nothing” with “a real zero”.

Practice Exercises

Exercise 1. List all orders, showing 0 when the amount is unknown.

Show answer
SELECT id, customer, COALESCE(amount, 0) AS amount
FROM orders;

Exercise 2. Count how many students have a CGPA and how many do not, in one query.

Show answer
SELECT COUNT(cgpa) AS graded,
       COUNT(*) - COUNT(cgpa) AS not_graded
FROM students;

Frequently Asked Questions

Is NULL the same as an empty string?

In standard SQL and most databases, no: '' is a known, empty value, while NULL means unknown. Oracle is an exception, as it treats an empty string as NULL.

Should columns allow NULL?

Only when a value can genuinely be missing. Add NOT NULL to columns that must always have a value, as shown in the constraints lesson.

Summary

  • NULL means unknown; any comparison with it is unknown.
  • Test with IS NULL / IS NOT NULL.
  • COALESCE supplies defaults; NULLIF creates NULLs on purpose.
  • Aggregates skip NULLs, and COUNT(*) differs from COUNT(column).

Next: SQL CASE Expression.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *