Working with NULL Values
# CHAPTER 11
Working with NULL Values
1. Introduction
In standard programming, if a user doesn't enter their phone number into a form, a developer might save it as a blank string"" or a zero 0. In SQL, a blank string is considered actual data (it is a string of length zero). A 0 is actual data (it is a number). But what happens when the data simply does not exist? We enter the void. In SQL, explicitly missing or unknown data is represented by the special marker NULL. In this chapter, we will learn how to handle NULL values and why they break standard mathematical logic.
2. Learning Objectives
By the end of this chapter, you will be able to:-
Define the concept of
NULLin relational databases.
-
Understand why
NULLcannot be compared using=or!=.
-
Filter for missing data using the
IS NULLoperator.
-
Filter out missing data using the
IS NOT NULLoperator.
-
Use the
COALESCE()function to safely replaceNULLvalues in output.
3. What exactly is NULL?
NULL is not a value. It is a *state*. It means "Unknown" or "Missing".
-
0means the value is zero.
-
""means the value is empty text.
-
NULLmeans we have absolutely no idea what the value is.
*Example:* If a new employee is hired but hasn't negotiated their salary yet, their salary column is NULL.
4. The Mathematical Trap of NULL
BecauseNULL means "Unknown", you cannot perform standard math or logic on it.
If you ask SQL, "Does Unknown equal 50?" SQL's answer is "Unknown".
*(Rule: You can NEVER use = or != with NULL!)*
5. The IS NULL Operator
To specifically check if a column's state is missing, you must use the special IS NULL operator.
6. The IS NOT NULL Operator
Conversely, if you are running a marketing campaign and only want to send texts to users who actually have a phone number on file, you use IS NOT NULL.
7. Safely Handling NULLs in Math (COALESCE)
If you try to add numbers in SQL: 100 + NULL = NULL. Any math involving NULL instantly destroys the entire calculation and turns the result into NULL.
If you are calculating a user's total compensation (Salary + Bonus), but they didn't get a bonus (it is NULL), the entire math fails.
To fix this, we use the incredibly powerful COALESCE() function. It takes a list of values and returns the first one that is NOT NULL.
8. Mini Project: Auditing the Database
Let's run a data cleanliness audit on an E-Commerce system.9. Common Mistakes
-
Confusing NULL with Zero: If a customer's
balanceis0, they owe you nothing. If theirbalanceisNULL, the banking system doesn't know their account state. Never use them interchangeably.
-
Using
IS NULLinINSERTStatements: When inserting data, you don't useIS NULL. You simply type the unquoted keywordNULL. Example:INSERT INTO users (name, phone) VALUES ('John', NULL);
10. Best Practices
-
NOT NULLConstraints: When architecting a database schema (Chapter 4 & 14), you can appendNOT NULLto a column definition (e.g.,email VARCHAR(100) NOT NULL). This physically prevents the database from ever accepting a row without an email, guaranteeing data integrity.
11. Exercises
-
1.
Why does the query
WHERE age = NULLfail to return results?
- 2. What SQL operator is explicitly required to filter out missing data?
12. SQL Challenges
Write a query to find all employees in thestaff table who have a department assigned, but whose manager_id is missing.
13. MCQ Quiz with Answers
In a Relational Database, what does the state of NULL explicitly represent?
If you execute a query containing WHERE phonenumber = NULL, what is the architectural result?
14. Interview Questions
-
Q: Explain the philosophical difference between storing an empty string
""in aVARCHARcolumn versus allowing that column to default toNULL.
-
Q: A financial query calculating
basesalary + annualbonusis returning blank rows for several employees. You discover those employees did not receive anannualbonusthis year. Explain the mechanical trap of NULL math causing this error, and how theCOALESCE()function solves it.
15. FAQs
Q: Do NULL values take up hard drive space? A: In modern databases like PostgreSQL and MySQL,NULL values take up virtually zero physical space on the hard drive (often just a single bit to flip a flag), making them highly efficient for optional data.
16. Summary
You have mastered the void. By understanding thatNULL is an undefined state that destroys mathematical equality, and by correctly implementing the IS NULL operator and the COALESCE() function, you guarantee that missing data will never crash your application logic or corrupt your financial reporting.