Sometimes a value is simply not known. A new customer did not give their country, a product has no category yet, an order has not been shipped so there is no shipping date. SQL marks a missing value with the special marker NULL.
NULL is not zero, and not empty text
NULL means "unknown" or "no value". It is different from:
0: a known number. The Bluetooth Speaker has a stock of0; we know there are none.'': an empty piece of text, which is still a known (empty) value.
In the Skope Shop database, Nyeri Stationers has NULL in its country column.
Testing for NULL: IS NULL
Here is the surprising part. You cannot find NULL with =:
No rows come back. A comparison with an unknown value is itself unknown, never true, so WHERE never keeps the row. Instead, use the special operators IS NULL and IS NOT NULL:
And the opposite, customers whose country is known:
= NULL and <> NULL never match anything. This is one of the most common SQL mistakes. Always write IS NULL or IS NOT NULL.Three-valued logic
Because of NULL, conditions in SQL have three possible outcomes: true, false and unknown. WHERE keeps only rows where the condition is true. That is why this query, which looks as if it should return every customer, does not:
SELECT name, country
FROM customers
WHERE country = 'Kenya' OR country <> 'Kenya';Try it Yourself »You get 11 rows, not 12. For Nyeri Stationers both comparisons are unknown, so the row is dropped. Keep this in mind whenever you filter a column that can hold NULL.
NULL in calculations
Any arithmetic with NULL gives NULL. If you don't know one number, you can't know the total:
Replacing NULL with COALESCE
The COALESCE() function returns the first value in its list that is not NULL. It is perfect for showing a friendly default:
COALESCE is standard SQL and works in every major database. You may also see older, database-specific versions of the same idea: IFNULL() in MySQL and SQLite, ISNULL() in SQL Server and NVL() in Oracle.
AS country gives the result column a name. Aliases are explained in Aliases.NULL and aggregate functions
Functions such as COUNT(column), SUM and AVG simply skip NULLs. COUNT(*) counts rows, while COUNT(country) counts only rows where country is not NULL:
The result is 12 and 11. You will learn these functions in Aggregate Functions.
When NULL is useful and when it isn't
NULL is the honest choice when a value really is unknown or does not apply. But too many nullable columns make queries harder to write correctly. When a value must always exist, such as a customer's name, declare the column NOT NULL when you create the table. See CREATE TABLE.
Find customers whose country is missing.
SELECT name FROM customers WHERE country ;Show each customer's country, or the text 'Unknown' when it is missing.
SELECT name, (country, 'Unknown') FROM customers;
SKOPE