Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace null with 0 in MySQL

Tags:

sql

null

mysql

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?

like image 676
NullVoxPopuli Avatar asked Aug 20 '10 16:08

NullVoxPopuli


People also ask

Is NULL and 0 the same in MySQL?

Conceptually, NULL means “a missing unknown value” and it is treated somewhat differently from other values. Because the result of any arithmetic comparison with NULL is also NULL , you cannot obtain any meaningful results from such comparisons. In MySQL, 0 or NULL means false and anything else means true.

How do you replace NULL values in a column in SQL?

The ISNULL Function is a built-in function to replace nulls with specified replacement values. To use this function, all you need to do is pass the column name in the first parameter and in the second parameter pass the value with which you want to replace the null value.

What to replace NULL values with?

Null values are replaced with mean/median.


2 Answers

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.

like image 73
Teekin Avatar answered Sep 20 '22 19:09

Teekin


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

like image 20
Arif Avatar answered Sep 21 '22 19:09

Arif