Replace null with 0 in MySQL

MysqlSqlNull

Mysql Problem Overview


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?

Mysql Solutions


Solution 1 - Mysql

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.

Solution 2 - Mysql

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).

Solution 3 - Mysql

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

Solution 4 - Mysql

There is the COALESCE method which return the first non-null parameter, in your case :

COALESCE(field, 0)

But you can use this if you want more :

COALESCE(field1, field2, 0)

Solution 5 - Mysql

MySQL:

SELECT COALESCE(Mycolumn, 0);

Solution 6 - Mysql

you can put the 0 value into your insert input method by casting it:(int)0

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNullVoxPopuliView Question on Stackoverflow
Solution 1 - MysqlTeekinView Answer on Stackoverflow
Solution 2 - MysqlArifView Answer on Stackoverflow
Solution 3 - MysqlAlex KhimichView Answer on Stackoverflow
Solution 4 - MysqlColin HebertView Answer on Stackoverflow
Solution 5 - MysqlSjoerdView Answer on Stackoverflow
Solution 6 - MysqlAlireza SaffarView Answer on Stackoverflow