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
0is a number: the stock is zero.''(empty string) is text with nothing in it.NULLmeans "no value / unknown". We don't know the phone number.
SELECT name, phone FROM customers;
The = NULL trap
You might expect this to find customers without phones:
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:
SELECT name, barangay
FROM customers
WHERE phone IS NULL;
SELECT name, phone
FROM customers
WHERE phone IS NOT NULL;
NULL in calculations
Any math with NULL gives NULL:
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:
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:
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:
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. 🙂
By Sir Reyel · Last updated 2026-12-04