Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: Typecasting NULL to 0

Tags:

sql

casting

mysql

Let us suppose the following table (e.g. a result of several inner join statements):

id | column_1 | column_2 ------------------------  1 |  1       |   2 |  2       | 2  3 |          | 3 

Which you could for example get from the following statement:

select a.id, t1.column_1, t2.column_2 from a left join t1 on a.id = t1.id left join t2 on a.id = t2.id 

Now, if i'd like to sum up t1.column_1 and t2.column_2 as follows

select      a.id,      t1.column_1,      t2.column_2,     (t1.column_1 + t2.column_2) as cumulated from a left join t1 on a.id = t1.id left join t2 on a.id = t2.id 

The reslut will look as follows:

id | column_1 | column_2 | cumulated ------------------------------------  1 |  1       | NULL     | NULL  2 |  2       | 2        | 4  3 |  NULL    | 3        | NULL 

My question basically is: is there a way to typecast NULL into 0 in order to do some math?

I have tried CONVERT(t1.column_1, SIGNED) and CAST(t1.column_1 as SIGNED), but a NULL stays a NULL.

like image 906
Pierre Spring Avatar asked Sep 17 '09 21:09

Pierre Spring


People also ask

How do you replace NULL with zero?

UPDATE [table] SET [column]=0 WHERE [column] IS NULL; Null Values can be replaced in SQL by using UPDATE, SET, and WHERE to search a column in a table for nulls and replace them. In the example above it replaces them with 0. Cleaning data is important for analytics because messy data can lead to incorrect analysis.

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.

Can integer be NULL in MySQL?

But the short answer is: yes, int columns can have NULL values.


1 Answers

Use IFNULL(column, 0) to convert the column value to zero.

Alternatively, the COALESCE function will do the same thing: COALESCE(column, 0), except

  1. COALESCE is ANSI-compliant, IFNULL is not
  2. COALESCE takes an arbitrary number of columns/values and will return the first non-null value passed to it.
like image 59
David Andres Avatar answered Oct 01 '22 01:10

David Andres