The short answer
Use COALESCE() to show 0 in place of NULL in a query:
SELECT product_name, COALESCE(stock_count, 0) AS stock_count
FROM products;
Rows where stock_count is NULL now show 0. The stored data doesn’t change.
Other databases’ versions
- MySQL:
IFNULL(stock_count, 0) - SQL Server:
ISNULL(stock_count, 0) - Oracle:
NVL(stock_count, 0)
Each of these returns the second value when the first is NULL. COALESCE works in all of these databases and takes more than two values. For more on the function, read what is coalesce() in sql.
Storing 0 in the table
To change the stored values, use an UPDATE with IS NULL:
UPDATE products
SET stock_count = 0
WHERE stock_count IS NULL;
Totals and averages change too
Replacing NULL with 0 changes the results of some functions:
AVG()skips NULL values but counts zeros, so storing 0 in place of NULL can lower an average.COUNT(stock_count)counts non-NULL values, so the new zeros are included in the count.SUM()returns NULL when every value it adds up is NULL. Wrapping it asCOALESCE(SUM(stock_count), 0)returns 0 in that case.
If you average several columns in each row, the NULL handling changes the answer as well. For that case, see how to calculate average for each row in sql.
Think before you store 0
NULL means no value was recorded. A 0 means a zero was recorded. If those mean different things in your data, keep NULL in the table and handle it in your queries instead.