Working with NULL Values
NULL is one of the most misunderstood concepts in SQL—and one of the most important! It's not zero, not an empty string, and not a space. NULL means "unknown" or "missing data." Understanding how NULL works is crucial because it behaves differently than any other value in SQL. Get this wrong, and your queries will silently return incorrect results!
📚 What You'll Learn
- What NULL actually means in SQL (it's not what you think!)
- How NULL behaves differently in comparisons
- Why
= NULLand<> NULLnever work - How to check for NULL properly using IS NULL
- How to check for NOT NULL (non-missing data)
- How NULL interacts with WHERE clauses
- How NULL affects aggregate functions (COUNT, SUM, AVG)
- Using COALESCE to replace NULL with default values
- Common mistakes beginners make (and how to avoid them)
- Real-world scenarios where NULL appears
- Hands-on practice exercises
1. What is NULL? (The Core Concept)
NULL represents the absence of a value. It's not:
- ❌ Not zero (0)
- ❌ Not an empty string ('')
- ❌ Not a space (' ')
- ❌ Not false
NULL literally means "I don't know" or "this information is missing."
💡 Real-World Example: Imagine a student enrollment form. Some students provide their phone number, others leave it blank. For students who didn't provide a phone number, the database stores NULL—not an empty string, not zero, but NULL, meaning "we don't know their phone number." It's genuinely missing information.
Example Table with NULL Values
| student_id | name | phone | graduation_year | |
|---|---|---|---|---|
| 1 | Alice Johnson | alice@uni.edu | 555-0100 | 2025 |
| 2 | Bob Smith | bob@uni.edu | NULL | 2024 |
| 3 | Carol Davis | NULL | 555-0102 | NULL |
| 4 | Diana Martinez | diana@uni.edu | 555-0103 | 2025 |
Notice Bob has no phone number (NULL), Carol has no email and no graduation year (both NULL). This is completely normal—databases often have missing information!
2. Why = NULL and <> NULL Never Work
This is where NULL gets tricky. In SQL logic, NULL equals nothing—not even itself!
The Wrong Way (Doesn't Work!)
-- ❌ WRONG: This returns ZERO rows, even though Bob's phone IS NULL!
SELECT name, phone
FROM students
WHERE phone = NULL;
Result: Returns 0 rows (nothing!)
⚠️ Why This Fails: In SQL, NULL means "unknown." When you ask "Is unknown equal to unknown?" the answer is... unknown! Not true, not false, but unknown. So the WHERE clause fails and returns nothing.
Understanding NULL Logic
Think about it philosophically:
Question: "Is Bob's unknown phone number equal to Carol's unknown phone number?"
Answer: We don't know! They might both have the same number, or completely different numbers. Since we don't know either number, we can't say they're equal.
SQL's Answer: NULL (unknown)
This is why NULL = NULL evaluates to NULL (unknown), not TRUE. And in a WHERE clause, NULL is treated as FALSE, so the row is excluded!
The Same Problem with <> (Not Equal)
-- ❌ ALSO WRONG: This also returns nothing!
SELECT name, phone
FROM students
WHERE phone <> NULL; -- Doesn't work!
Same logic: "Is unknown not equal to unknown?" → Unknown! Not TRUE, so no rows returned.
3. The Right Way to Check for NULL
SQL has special operators specifically for NULL: IS NULL and IS NOT NULL
Finding NULL Values
-- ✅ CORRECT: Find students with no phone number
SELECT name, phone
FROM students
WHERE phone IS NULL;
Result:
| name | phone |
|---|---|
| Bob Smith | NULL |
✅ Success! We found Bob, whose phone number is NULL.
Finding Non-NULL Values (Data That Exists)
-- ✅ CORRECT: Find students who DID provide a phone number
SELECT name, phone
FROM students
WHERE phone IS NOT NULL;
Result:
| name | phone |
|---|---|
| Alice Johnson | 555-0100 |
| Carol Davis | 555-0102 |
| Diana Martinez | 555-0103 |
✅ Returns everyone who has a phone number (excluding Bob).
💡 Memory Trick: Think "IS" for "IS NULL" and "IS NOT NULL"—never use equals signs with NULL!
4. How NULL Interacts with WHERE Clauses
NULL can create unexpected results in WHERE clauses. Let's see some surprising behaviors:
Example: Students Graduating Before 2025
SELECT name, graduation_year
FROM students
WHERE graduation_year < 2025;
Result:
| name | graduation_year |
|---|---|
| Bob Smith | 2024 |
Notice: Carol (who has NULL graduation_year) is NOT included!
⚠️ Important: NULL is excluded from all comparison operations (<, >, <=, >=, =, <>). If you want to include rows with NULL, you must explicitly check for it!
Including NULL in Your Results
-- Include students graduating before 2025 OR with unknown graduation year
SELECT name, graduation_year
FROM students
WHERE graduation_year < 2025 OR graduation_year IS NULL;
Now Carol (with NULL) would be included!
5. How NULL Affects Aggregate Functions
Aggregate functions (COUNT, SUM, AVG, MIN, MAX) handle NULL in specific ways:
COUNT Behavior with NULL
COUNT(*) - All Rows
SELECT COUNT(*)
FROM students;
Result: 4 (counts all rows, including NULL)
COUNT(column) - Non-NULL Only
SELECT COUNT(phone)
FROM students;
Result: 3 (excludes Bob's NULL phone)
💡 Key Difference: COUNT(*) counts rows, COUNT(column_name) counts non-NULL values in that column. This is a common interview question!
SUM, AVG, MIN, MAX with NULL
These functions ignore NULL values completely:
-- Assume we have a grades column with some NULLs
SELECT
COUNT(*) as total_students, -- Counts all rows
COUNT(grade) as students_with_grades, -- Counts non-NULL grades
AVG(grade) as average_grade -- Averages only non-NULL grades
FROM students;
If 3 students have grades (85, 90, 75) and 1 has NULL:
COUNT(*)= 4 (all students)COUNT(grade)= 3 (students with grades)AVG(grade)= 83.33 (average of 85, 90, 75 — NULL ignored)
6. Using COALESCE to Handle NULL
COALESCE returns the first non-NULL value from a list. It's perfect for replacing NULL with a default value!
Basic Syntax
COALESCE(value1, value2, value3, ...)
Returns the first value that's not NULL.
Example: Providing Default Values
SELECT
name,
COALESCE(phone, 'No phone provided') AS phone_display,
COALESCE(email, 'No email on file') AS email_display
FROM students;
Result:
| name | phone_display | email_display |
|---|---|---|
| Alice Johnson | 555-0100 | alice@uni.edu |
| Bob Smith | No phone provided | bob@uni.edu |
| Carol Davis | 555-0102 | No email on file |
Instead of showing NULL (which looks unprofessional), we display user-friendly messages!
COALESCE with Multiple Fallbacks
SELECT
name,
COALESCE(mobile_phone, home_phone, work_phone, 'No contact number') AS contact
FROM students;
Returns the first non-NULL phone number, or "No contact number" if all are NULL.
7. Common Beginner Mistakes
Mistake #1: Using = or <> with NULL
-- ❌ WRONG
WHERE phone = NULL
WHERE email <> NULL
-- ✅ CORRECT
WHERE phone IS NULL
WHERE email IS NOT NULL
Mistake #2: Forgetting NULL Excludes Rows
-- ❌ INCOMPLETE: Misses students with NULL graduation_year
SELECT name FROM students WHERE graduation_year >= 2024;
-- ✅ BETTER: Explicitly decide what to do with NULL
SELECT name FROM students
WHERE graduation_year >= 2024 OR graduation_year IS NULL;
Mistake #3: Treating NULL as Zero or Empty String
-- ❌ WRONG: NULL is NOT zero
WHERE age = 0 -- Won't find NULL ages
-- ❌ WRONG: NULL is NOT empty string
WHERE email = '' -- Won't find NULL emails
-- ✅ CORRECT
WHERE age IS NULL
WHERE email IS NULL
Mistake #4: Not Understanding COUNT Differences
-- These give DIFFERENT results!
SELECT COUNT(*) FROM students; -- Counts all rows (4)
SELECT COUNT(phone) FROM students; -- Counts non-NULL phones (3)
Mistake #5: Forgetting NULL in Calculations
-- Any math with NULL returns NULL!
SELECT 10 + NULL; -- Returns NULL (not 10!)
SELECT 5 * NULL; -- Returns NULL (not 0!)
SELECT NULL / 2; -- Returns NULL
Use COALESCE to handle NULL in calculations:
-- Treat NULL as 0 in calculations
SELECT COALESCE(bonus, 0) + salary AS total_compensation
FROM employees;
8. Real-World Scenarios Where NULL Appears
- Optional fields: Middle name, phone number, apartment number
- Future dates: Graduation date for current students
- Pending data: Grade not yet assigned, order not yet shipped
- Inapplicable data: Spouse name for unmarried person
- Unknown information: Birth date, original purchase price
- Partial records: Incomplete form submissions
💡 Professional Tip: When designing databases, think carefully about which columns should allow NULL. Required information (like name, email) should be NOT NULL. Optional information (like phone, middle name) can allow NULL.
9. 🎯 Hands-On Practice Exercises
Exercise 1: Finding NULL Values
Task: Write a query to find all students who don't have an email address on file.
Show Answer
SELECT name, email
FROM students
WHERE email IS NULL;
Exercise 2: Finding Non-NULL Values
Task: Find all students who HAVE provided a phone number.
Show Answer
SELECT name, phone
FROM students
WHERE phone IS NOT NULL;
Exercise 3: Combining NULL with Other Conditions
Task: Find students who either graduated in 2024 OR have no graduation year recorded.
Show Answer
SELECT name, graduation_year
FROM students
WHERE graduation_year = 2024 OR graduation_year IS NULL;
Exercise 4: Using COALESCE
Task: Display student names and phone numbers, but show "Not Provided" if phone is NULL.
Show Answer
SELECT
name,
COALESCE(phone, 'Not Provided') AS phone_display
FROM students;
Exercise 5: COUNT with NULL
Task: Count how many students have phone numbers vs. total students.
Show Answer
SELECT
COUNT(*) AS total_students,
COUNT(phone) AS students_with_phones,
COUNT(*) - COUNT(phone) AS students_without_phones
FROM students;
Remember: COUNT(*) counts rows, COUNT(column) counts non-NULL values!
Challenge Exercise: Complete Contact Information
Task: Find students who have BOTH email AND phone number (neither is NULL).
Show Answer
SELECT name, email, phone
FROM students
WHERE email IS NOT NULL AND phone IS NOT NULL;
Note: Both conditions must be true (AND logic).
📝 Key Takeaways
- NULL means "unknown" or "missing" — not zero, not empty string
- Never use
= NULLor<> NULL— they don't work! - Always use IS NULL to check for NULL values
- Always use IS NOT NULL to check for existing values
- NULL is excluded from all comparison operations (<, >, <=, >=)
COUNT(*)counts all rows,COUNT(column)excludes NULL- SUM, AVG, MIN, MAX ignore NULL values automatically
- Use COALESCE to replace NULL with default values
- Any math operation with NULL returns NULL
- NULL = NULL evaluates to NULL (unknown), not TRUE
🚀 What's Next?
Excellent work mastering NULL values! Next, you'll learn about pattern matching with LIKE, which lets you search for partial text matches. Want to find all students whose names start with "A" or emails ending in ".edu"? LIKE is your tool!
Up next: Pattern Matching with LIKE - Searching Text