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.
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.
Int is a primitive and can't be null.
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 .
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.
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With