Write a query to retrieve customers who do not have an email.
Objective:
Write a SQL query to retrieve customers who do not have an email.
Step 1: Create the customers
Table
Let’s first create a customers
table with the following fields:
CREATE TABLE customers (
id INT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
);
Step 2: Insert Dummy Data
Let’s insert some sample records, including some without emails (i.e., NULL
values):
INSERT INTO customers (id, name, email) VALUES
(1, 'John Doe', 'john@example.com'),
(2, 'Jane Smith', NULL),
(3, 'Alice Johnson', 'alice@example.com'),
(4, 'Bob Brown', NULL),
(5, 'Mike Davis', 'mike.davis@example.com');
Step 3: Write the SQL Query
Now, to retrieve customers who do not have an email, we need to filter the records where the email
is NULL
.
SELECT * FROM customers
WHERE email IS NULL;
Output (Result)
id |
name |
email |
2 |
Jane Smith |
NULL |
4 |
Bob Brown |
NULL |
Why IS NULL
instead of = NULL
?
In SQL, to check for NULL
values you must use:
IS NULL
— to find rows where a column is null
IS NOT NULL
— to find rows where a column has a value
Because = NULL
does not work (it always evaluates to unknown).