I am getting NULL values in the results of an operation in MySQL.
Is there a way to convert the NULL values into the value 0?
Yes, by using COALESCE.
SELECT COALESCE(null_column, 0) AS null_column FROM whatever;
COALESCE goes through the list of values you give it, and returns the first non-null value.
COALESCE is ANSI, supported by SQL Server 2000+, Oracle 9i+, MySQL 4.1+, dunno the version of PostgreSQL or SQLite...coalesce(). Case and point, it was in MySQL 3.23 which is about as close to the bottom of the barrel as you can get.I am adding this answer because no one mentioned IFNULL function
You can use IFNULL
SELECT IFNULL(column_name, 0) FROM table_name;
IFNULL will return column's value (if it has something other than NULL) otherwise second parameter passed (in this case 0).
SELECT IFNULL(column1, column2) FROM table. or SELECT IFNULL(column1, 0) AS alias1, IFNULL(column2, 0) AS alias2 FROM table. BUT if you want to use more than 2 columns in one expression then you will need to use COALESCE like this SELECT COALESCE(column1, column2, column3, column4, 0) FROM table. COALESCE will return first non-null value in the parameters.If you messed up and have NULLs in existing table layout and want zeros, here is solution:
UPDATE `table` SET `somefield`=0 WHERE `somefield` is null