MySQL IFNULL() takes two expressions and if the first expression is not NULL, it returns the first expression. Otherwise, it returns the second expression. Depending on the context in which it is used, it returns either numeric or string value. An expression.
We can return 0 for NULL in MySQL with the help of IFNULL() method. The syntax of IFNULL() is as follows. IFNULL(YOUREXPRESSION,0);
The MySQL ISNULL() function is used to check for any NULL values in the expression passed to it as a parameter. If the expression has/results to NULL, it displays 1. If the expression does not have or result in NULL, the function returns 0.
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.
Instead of COALESCE(a.addressid,0) AS addressexists
, use CASE
:
CASE WHEN a.addressid IS NOT NULL
THEN 1
ELSE 0
END AS addressexists
or the simpler:
(a.addressid IS NOT NULL) AS addressexists
This works because TRUE
is displayed as 1
in MySQL and FALSE
as 0
.
SELECT c.name, IF(a.addressid IS NULL,0,1) AS addressexists
FROM customers c
LEFT JOIN addresses a ON c.customerid = a.customerid
WHERE customerid = 123
Careful if you're coming from C/C++ and expecting this to work:
select if(name, 1, 0) ..
Even if 'name' is not NULL, unlike in C, a false-condition still triggers and the above statement returns 0. Thus, you have to remember to explicitly check for NULL or empty string:
select if(name is null or name = '', 0, 1)
PS Eugen's example up above is correct, but I wanted to clarify this nuance as it caught me by surprise.
SELECT
c.name,
CASE WHEN a.addressid IS NULL THEN 0 ELSE 1 END AS addressexists
FROM customers c
LEFT JOIN addresses a ON c.customerid = a.customerid
WHERE customerid = 123
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