SQL NULL values

SQL NULL Values (Beginner → Advanced)
In SQL, NULL represents missing, unknown, or not applicable data.
It is not the same as 0, empty string (''), or false—this difference is very important for correctness and interviews.
What is NULL in SQL?
NULLmeans no value or unknown value.
Example of NULL Values
Table: employees
| id | name | salary | |
|---|---|---|---|
| 1 | Rahul | rahul@gmail.com | 50000 |
| 2 | Amit | NULL | 45000 |
| 3 | Neha | neha@gmail.com | NULL |
Amit has no email
Neha’s salary is unknown
Inserting NULL Values
NULLis explicitly inserted- Column must allow
NULL
Checking NULL Values (Very Important)
WRONG (Never works)
CORRECT
NOT NULL
NULLmust be checked usingIS NULL/IS NOT NULL
NULL with Comparison Operators
Rows with salary = NULL are ignored
Why?
Because any comparison with NULL results in UNKNOWN.
NULL and Aggregate Functions
Table
| salary |
|---|
| 50000 |
| 40000 |
| NULL |
| Function | Behavior |
|---|---|
COUNT(column) | Ignores NULL |
SUM() | Ignores NULL |
AVG() | Ignores NULL |
MIN() / MAX() | Ignore NULL |
Handling NULL with COALESCE()
Replace NULL with a value
- If
salaryisNULL, it becomes0
IFNULL() / NVL() (Database Specific)
MySQL
Oracle
NULL with WHERE + Logic
- Rows with
salary = NULLare excluded
Correct Handling
NULL vs DEFAULT
| Feature | NULL | DEFAULT |
|---|---|---|
| Meaning | Unknown / Missing | Predefined value |
| Value exists? | No | Yes |
| Used when | Data not available | Value not provided |
- Better than allowing
NULLin many cases
NOT NULL Constraint
- Prevents
NULLvalues - Ensures data integrity
Common Mistakes
- Using
=withNULL ForgettingIS NULLAssumingNULL= 0- Ignoring
NULLin calculations - Wrong
COUNT()usage
Interview Questions (Must Prepare)
What is
NULLin SQL?Difference between
NULLand0?How to check
NULLvalues?Does
COUNT(*)countNULL?How does
NULLbehave in comparisons?Difference between
NULLandDEFAULT?
Real-Life Use Cases
Optional user fields (email, phone)
Missing data in reports
Incomplete transactions
API data storage
Data migration handling
Summary
NULLmeans no value / unknown- Use
IS NULL/IS NOT NULL Comparisons withNULLreturn UNKNOWN- Aggregates ignore
NULL(exceptCOUNT(*)) - Use
COALESCE()to handleNULLsafely - Essential for correct SQL logic & interviews
