SQL NULL Values
Introduction
In SQL databases, a NULL
value represents missing or unknown data. Unlike other values, NULL
is not zero, an empty string, or a space - it's the absence of any value. Understanding how to work with NULL
values is crucial for effective database management and query writing.
Think of NULL
as a placeholder that says, "This information is not available." For example, if a customer hasn't provided their phone number, that field would contain a NULL
value rather than being empty or containing a default value.
Understanding NULL Values
What NULL Represents
NULL
indicates missing, unknown, or inapplicable dataNULL
is not equivalent to zero or an empty stringNULL
is not equal to anotherNULL
(two unknowns aren't necessarily the same)
How NULL Behaves
The most important thing to understand about NULL
values is that they behave differently in comparisons:
NULL
is not equal to anything, including anotherNULL
NULL
is not greater than or less than any value- Any arithmetic operation involving
NULL
results inNULL
- Any comparison with
NULL
using standard operators (=
,<
,>
) yieldsUNKNOWN
(notTRUE
orFALSE
)
Testing for NULL Values
Since NULL
cannot be compared using the equality operator (=
), SQL provides special operators to test for NULL
values.
Using IS NULL and IS NOT NULL
To check if a column contains a NULL
value:
SELECT column_name, another_column
FROM table_name
WHERE column_name IS NULL;
To find rows where a column is not NULL
:
SELECT column_name, another_column
FROM table_name
WHERE column_name IS NOT NULL;
Example: Finding Missing Contact Information
Let's say we have a customers
table with contact information:
-- Creating a sample customers table
CREATE TABLE customers (
customer_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
email VARCHAR(100),
phone VARCHAR(20)
);
-- Inserting sample data
INSERT INTO customers VALUES
(1, 'John', 'Smith', '[email protected]', '555-1234'),
(2, 'Sarah', 'Johnson', '[email protected]', NULL),
(3, 'Michael', 'Brown', NULL, '555-5678'),
(4, 'Emily', 'Davis', '[email protected]', '555-9012'),
(5, 'David', 'Wilson', NULL, NULL);
Now, to find customers with missing phone numbers:
SELECT customer_id, first_name, last_name
FROM customers
WHERE phone IS NULL;
Output:
customer_id | first_name | last_name
------------|------------|----------
2 | Sarah | Johnson
5 | David | Wilson
To find customers with both email and phone information:
SELECT customer_id, first_name, last_name
FROM customers
WHERE email IS NOT NULL AND phone IS NOT NULL;
Output:
customer_id | first_name | last_name
------------|------------|----------
1 | John | Smith
4 | Emily | Davis