Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Cast NULL to integer 0

How can I cast something that returns NULL to 0?

If this is my query: select col from table; would this be the right way to do it: select cast(col as unsigned integer) from table;?

Thank you.

like image 749
Francisc Avatar asked Oct 31 '10 00:10

Francisc


People also ask

How do I change NULL to zero in MySQL?

Use IFNULL or COALESCE() function in order to convert MySQL NULL to 0. Insert some records in the table using insert command. Display all records from the table using select statement.

Can NULL be CAST to int?

Int is a primitive and can't be null.

How do I show NULL values as zero in SQL?

When selecting data from a table, there might be some NULL values that you don't want to show, or you want to replace it with 0 for the aggregate functions. Then you can use COALESCE to replace the NULL with 0. For example, we have the table salaries with 5 columns: emp_no , from_date , to_date , salary , bonus .

What is CAST () in MySQL?

The MySQL CAST() function is used for converting a value from one datatype to another specific datatype. The CAST() function accepts two parameters which are the value to be converted and the datatype to which the value needs to be converted.


2 Answers

You'd probably want to use the COALESCE() function:

SELECT COALESCE(col, 0) FROM `table`; 

COALESCE() returns the first non-NULL value in the list, or NULL if there are no non-NULL values.

Test case:

CREATE TABLE `table` (id int, col int);  INSERT INTO `table` VALUES (1, 100); INSERT INTO `table` VALUES (2, NULL); INSERT INTO `table` VALUES (3, 300); INSERT INTO `table` VALUES (4, NULL); 

Result:

+------------------+ | COALESCE(col, 0) | +------------------+ |              100 | |                0 | |              300 | |                0 | +------------------+ 4 rows in set (0.00 sec) 
like image 197
Daniel Vassallo Avatar answered Oct 09 '22 02:10

Daniel Vassallo


You can also use the IFNULL() function:

SELECT IFNULL(col, 0) FROM `table`; 

IFNULL(expr1, expr2) returns the first expression if it's not null, else returns the second expression.

Test case:

CREATE TABLE `table` (id int, col int);  INSERT INTO `table` VALUES (1, 100); INSERT INTO `table` VALUES (2, NULL); INSERT INTO `table` VALUES (3, 300); INSERT INTO `table` VALUES (4, NULL); 

Result:

+----------------+ | IFNULL(col, 0) | +----------------+ |            100 | |              0 | |            300 | |              0 | +----------------+ 4 rows in set (0.00 sec) 
like image 44
Mike Causer Avatar answered Oct 09 '22 03:10

Mike Causer