SQL FOUNDATIONS:NULL Handling
Work safely with missing values using IS NULL and COALESCE.
SQL NULL Handling Explained with Examples + Practice Questions
What is NULL
NULL represents missing or unknown data.
It is not:
- 0
- empty string
- false
It means no value exists.
When to Use NULL Handling
- When data is missing
- When filtering incomplete records
- When working with joins and optional relationships
NULL-related questions are very common in SQL interviews.
Example Dataset
Table: employees
Checking NULL Values
Incorrect Way
sqlSELECT * FROM employeesWHERE department = NULL;
This will NOT work.
Correct Way
sqlSELECT * FROM employeesWHERE department IS NULL;
Checking NOT NULL
sqlSELECT * FROM employeesWHERE department IS NOT NULL;
NULL in Conditions
NULL cannot be compared using:
- =
- !=
Always use:
- IS NULL
- IS NOT NULL
Handling NULL with Functions
Using COALESCE (Replace NULL)
sqlSELECT name, COALESCE(department, 'Not Assigned') AS deptFROM employees;
Replaces NULL with a default value.
Using IFNULL (MySQL specific)
sqlSELECT name, IFNULL(salary, 0) AS salaryFROM employees;
NULL in Aggregations
sqlSELECT AVG(salary) FROM employees;
NULL values are ignored. Only valid numbers are used.
NULL in COUNT
sqlSELECT COUNT(department) FROM employees;
Counts only non-null values.
sqlSELECT COUNT(*) FROM employees;
Counts all rows.
NULL with JOIN
sqlSELECT e.nameFROM employees eLEFT JOIN departments dON e.department = d.nameWHERE d.name IS NULL;
Used to find unmatched records.
Key Concepts
- NULL means missing data
- Cannot use = or != with NULL
- Use IS NULL / IS NOT NULL
- Use COALESCE to replace NULL
- NULL is ignored in most aggregations
Common Questions (FAQ)
What is NULL in SQL
NULL represents missing or unknown data.
Why = NULL does not work
Because NULL is not a value, it is a state.
How to replace NULL values
Use COALESCE or IFNULL.
Does COUNT include NULL
COUNT(column) ignores NULL, COUNT(*) includes all rows.
Internal Learning Links
- Learn WHERE filtering
- Learn JOINs
- Learn Aggregations
Practice CTA
Practice NULL-based SQL problems on Schoolabe to handle real-world messy data.
NULL Handling Missions
Solve exercises in sequence to unlock the next mission.
Salary is NOT NULL
Retrieve employees where salary is NOT NULL.
Replace NULL dept
Replace NULL department with 'Unknown'.
Replace NULL salary
Replace NULL salary with 0.
Count non-null dept
Count employees where department is NOT NULL.
Average salary
Find average salary ignoring NULL values.
Dept or salary NULL
Retrieve employees where department is NULL or salary is NULL.
Dept not null and salary > 50000
Retrieve employees where department is NOT NULL and salary > 50000.
Replace NULL salary 10000
Retrieve employees and replace NULL salary with 10000.
Unassigned employees via JOIN
Find employees who are not assigned to any department using JOIN logic.