MySQL NULL Values
MySQL NULL Values: Testing and Handling Missing Data
In MySQL, NULL represents a missing, unknown, or inapplicable value—never zero (0) and never an empty string (''). Because NULL means unknown, standard equality operators like = and != cannot test for it.
Testing for NULL Correctly
Use IS NULL to find rows with missing values and IS NOT NULL to find rows that contain a real value:
SELECT columns
FROM table_name
WHERE column_name IS NULL;
Practical SQL Example
This query finds pending rows in demo_orders that have not been shipped yet (shipped_at IS NULL) and shipped orders that already have a timestamp.
-- Find unshipped demo orders
SELECT id, customer_id, status, shipped_at
FROM demo_orders
WHERE shipped_at IS NULL;
-- Find orders that have already shipped
SELECT id, customer_id, shipped_at
FROM demo_orders
WHERE shipped_at IS NOT NULL;
| id | customer_id | status | shipped_at |
|---|---|---|---|
| 104 | 7 | pending | NULL |
| 108 | 12 | on_hold | NULL |
Common Mistakes with NULL
- Using
= NULLor!= NULL: Both evaluate toUNKNOWNand match zero rows. Always useIS NULL,IS NOT NULL, or MySQL's null-safe equality operator when comparing two nullable columns. - Arithmetic Propagation: Any math operation with
NULL(such asprice + NULL) yieldsNULLacross the entire expression. Wrap optional numbers inCOALESCE(discount, 0)before adding or subtracting totals. - Confusing
COUNT(*)andCOUNT(col):COUNT(*)counts every row includingNULLs, whileCOUNT(shipped_at)skips rows whereshipped_atisNULL. - Index Scans on
IS NULL: Standard B-tree indexes in MySQL still indexNULLvalues, soWHERE shipped_at IS NULLstays fast when selective.
Frequently Asked Questions
Is an empty string '' the same as NULL in MySQL?
No, '' is a known zero-length string value, whereas NULL means no value was provided at all.
How does ORDER BY sort NULL values in MySQL?
In ORDER BY col ASC, MySQL places NULL values first; in ORDER BY col DESC, NULL values appear last.
Which function replaces NULL with a fallback value?
Use COALESCE(col, fallback) (ANSI SQL standard) or IFNULL(col, fallback) to replace NULL during output formatting.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.