Lesson

MySQL NULL Values

10 min reading
Free Course

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 = NULL or != NULL: Both evaluate to UNKNOWN and match zero rows. Always use IS NULL, IS NOT NULL, or MySQL's null-safe equality operator when comparing two nullable columns.
  • Arithmetic Propagation: Any math operation with NULL (such as price + NULL) yields NULL across the entire expression. Wrap optional numbers in COALESCE(discount, 0) before adding or subtracting totals.
  • Confusing COUNT(*) and COUNT(col): COUNT(*) counts every row including NULLs, while COUNT(shipped_at) skips rows where shipped_at is NULL.
  • Index Scans on IS NULL: Standard B-tree indexes in MySQL still index NULL values, so WHERE shipped_at IS NULL stays 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.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
MySQL Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum