NULL Values
What is a NULL Value?
A field with a NULL value has no value. It is not the same as zero or an empty string: it means "unknown" or "missing".
In the demo data, Golden Spoon has a NULL city, order 105 has a NULL employee, and Almonds has a NULL stock.
How to Test for NULL Values?
You cannot use = or <> with NULL; any comparison with NULL gives "unknown", which is treated as false. Use IS NULL and IS NOT NULL.
Wrong
This returns no rows, even though a NULL city exists:
SELECT * FROM Customers
WHERE City = NULL;Result: 0 rows
| CustomerID | CustomerName | ContactName | City | Country |
|---|
Example (IS NULL)
The correct way: find customers whose city is missing:
SELECT CustomerName, City FROM Customers
WHERE City IS NULL;Result: 1 row
| CustomerName | City |
|---|---|
| Golden Spoon | NULL |
IS NOT NULL
Example
Orders that were handled by an employee:
SELECT OrderID, EmployeeID FROM Orders
WHERE EmployeeID IS NOT NULL;Result: 7 rows
| OrderID | EmployeeID |
|---|---|
| 101 | 2 |
| 102 | 3 |
| 103 | 2 |
| 104 | 3 |
| 106 | 2 |
| 107 | 3 |
| 108 | 2 |
NULL in Calculations
Any arithmetic with NULL gives NULL. Aggregate functions like SUM and AVG skip NULL values.
Example
The stock value of Almonds is NULL because its stock is NULL:
SELECT ProductName, Stock, Price * Stock AS StockValue FROM Products;Result: 6 rows
| ProductName | Stock | StockValue |
|---|---|---|
| Basmati Rice 5kg | 120 | 1500 |
| Green Tea 100 bags | 300 | 2025 |
| Olive Oil 1L | 80 | 799.2 |
| Dark Chocolate | 0 | 0 |
| Espresso Beans 1kg | 45 | 810 |
| Almonds 500g | NULL | NULL |
Tip: Use COALESCE(Stock, 0) to treat missing values as zero. See NULL Functions in the Functions module.