How to check null values in SQL
Overview
In SQL, NULL represents a missing or unknown value.
To check for missing values in SQL, we use IS NULL expression.
The IS NULL operator, when used in conjunction with WHERE, helps us figure out what data is missing.
Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IS NULL;
Code
Let’s assume we have a table called Person with the columns ID, name, age, state, and gender.
Now, we want to get the names of all people whose ages are missing from the Person table.
How do we get this information from our table?
The following code shows how to do this using the IS NULL operator in SQL.
CREATE TABLE Person (ID int,name varchar(100),age int,gender varchar(10),state varchar(15));-- Insert dataINSERT INTO PersonVALUES (1,'Sharon Peller','16','Female','Kogi');INSERT INTO PersonVALUES (2,'Paul Dons', NULL,'Male','Lagos');INSERT INTO PersonVALUES (3,'Ameera Abedayo','28','Female','Imo');INSERT INTO PersonVALUES (4,'Maria Elijah',NULL,'Female','Lagos');INSERT INTO PersonVALUES (5,'David Hassan',NULL,'Male','Abuja');INSERT INTO PersonVALUES (6,'Niniola Disu','28','Female','Lagos');INSERT INTO PersonVALUES (7,'Praise Dominion','16','Female','Ibadan');INSERT INTO PersonVALUES (8,'Joe Smith','16','Male','Lagos');-- QuerySELECT nameFROM PersonWHERE age IS NULL;
Explanation
- Lines 1–7: We create a table called
Personwith the columnsID,name,age,gender, andstate. - Lines 10–25: We insert data into the
Persontable. - Lines 28–30: We filter the missing data using the
IS NULLoperator with theWHEREkeyword.