Aral Code

Filtering & Sorting Lesson 10 of 21

SQL NULL Values — IS NULL, IS NOT NULL and COALESCE

Understand NULL (a missing value), find it with IS NULL and IS NOT NULL, avoid the = NULL trap, and replace it with COALESCE or IFNULL.

Sometimes a value is simply unknown or missing: a customer who didn't give a phone number, a student who hasn't taken a test yet. Databases represent this with a special marker called NULL.

NULL is not zero or empty

  • 0 is a number: the stock is zero.
  • '' (empty string) is text with nothing in it.
  • NULL means "no value / unknown". We don't know the phone number.
SQL Some customers have no phone number
SELECT name, phone FROM customers;

The = NULL trap

You might expect this to find customers without phones:

SQL This returns nothing!
SELECT name FROM customers WHERE phone = NULL;

It returns no rows. Comparing anything with NULL, even NULL itself, gives "unknown", never true. NULL means "we don't know", and SQL can't say whether an unknown value equals something.

IS NULL and IS NOT NULL

Use these special operators instead:

SQL Customers without a phone number
SELECT name, barangay
FROM customers
WHERE phone IS NULL;
SQL Customers we can text
SELECT name, phone
FROM customers
WHERE phone IS NOT NULL;

NULL in calculations

Any math with NULL gives NULL:

SQL NULL spreads through calculations
SELECT 10 + NULL AS a, NULL * 5 AS b, 'Hi ' || NULL AS c;

COALESCE: a replacement value

COALESCE(value, replacement) returns the first value that isn't NULL. It's perfect for showing something friendlier than NULL:

SQL Show 'no number' instead of NULL
SELECT name, COALESCE(phone, 'no number') AS contact
FROM customers;

MySQL and SQLite also have IFNULL(value, replacement), which does the same for two values. SQL Server uses ISNULL. COALESCE works in all of them.

NULL and aggregate functions

Functions like COUNT(column) and AVG(column) skip NULLs. COUNT(*) counts all rows:

SQL Counting with and without NULLs
SELECT COUNT(*) AS customers,
       COUNT(phone) AS with_phone
FROM customers;

Missing rows are different from NULL

In our grades table, student 8 has no English grade. That's not a NULL value; the row simply doesn't exist:

SQL Grades of student 8
SELECT * FROM grades WHERE student_id = 8;

NULLs appear when you combine tables and a match is missing. You'll see this in the LEFT JOIN lesson.

Preventing NULLs

When creating a table, you can forbid NULL in important columns with NOT NULL, so a product can never be saved without a name:

CREATE TABLE products (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  price REAL NOT NULL
);

Quick Quiz

Check what you learned. Walang grade ito, practice lang. 🙂

1. How do you find rows where phone has no value?
2. What is 5 + NULL?
3. What does COALESCE(phone, 'none') return when phone is NULL?
4. Which counts only rows where phone is not NULL?

By Sir Reyel · Last updated 2026-12-04