SQL NULL Values
NULL in SQL means no value or unknown. It is not the same as zero or an empty string. When a column has no data entered for a particular row, it stores NULL.
Think of NULL like a blank field on a form — the person did not fill it in. It is not zero, it is simply missing.
The Reference Table
| StudentID | StudentName | Age | City |
|---|---|---|---|
| 1 | Ravi Sharma | 20 | Delhi |
| 2 | Priya Mehta | 22 | NULL |
| 3 | Arjun Nair | NULL | Chennai |
| 4 | Sneha Kapoor | 21 | Pune |
Checking for NULL with IS NULL
You cannot use = NULL to check for NULL values. You must use IS NULL.
MySQL Query
-- Find students where City is missing
SELECT * FROM Students WHERE City IS NULL;MS SQL Server Query
-- Find students where City is missing
SELECT * FROM Students WHERE City IS NULL;Checking for NOT NULL
MySQL Query
-- Find students where City has a value
SELECT * FROM Students WHERE City IS NOT NULL;MS SQL Server Query
-- Find students where City has a value
SELECT * FROM Students WHERE City IS NOT NULL;Replacing NULL with a Default Value
Sometimes you want to display a default value instead of NULL in the output. The function name differs between MySQL and MS SQL Server.
MySQL Query
-- IFNULL replaces NULL with 'Not Provided' in MySQL
SELECT StudentName, IFNULL(City, 'Not Provided') AS City
FROM Students;MS SQL Server Query
-- ISNULL replaces NULL with 'Not Provided' in MS SQL Server
SELECT StudentName, ISNULL(City, 'Not Provided') AS City
FROM Students;COALESCE — Works in Both Databases
COALESCE is the ANSI standard function that works the same in both MySQL and MS SQL Server. It returns the first non-NULL value from a list.
MySQL Query
SELECT StudentName, COALESCE(City, 'Not Provided') AS City
FROM Students;MS SQL Server Query
SELECT StudentName, COALESCE(City, 'Not Provided') AS City
FROM Students;Key Points
NULLmeans "no value" — it is not zero, not an empty string, just unknown.- Use
IS NULLandIS NOT NULL— never use= NULL. - MySQL uses
IFNULL(column, default)to replace NULL with a default value. - MS SQL Server uses
ISNULL(column, default)— the same purpose, different name. COALESCE(column, default)is the ANSI standard and works in both databases.
