MySQL server version 5.0.45. Consider the following:
( SELECT CASE
WHEN t.group_id = 12 THEN 'yes'
ELSE 'no'
END
FROM sample_table t
WHERE t.user_id = 2
AND t.group_id = 12 ) as foo
This subquery of a larger statement works as I'd expect, yielding a 'yes' or 'no' string value most of the time. It's not ideal, but that's what you get for working on someone else's code!
However, sometimes the select can legitimately return an empty set, in which case foo is set to NULL. This does not actually break the application, but it's irritating. Is there a way I can guarantee that foo will always be either 'yes' or 'no', even if there are no matching rows in the table?
The CASE statement cannot have an ELSE NULL clause, and it is terminated with END CASE instead of END . For the first syntax, case_value is an expression.
If there is 'empty set' in the result set of MySQL query then it means that MySQL is returning no rows and no error also in the query.
Answer: MySQL provides a CASE Statement that can be used to retrieve data against a column value based on conditions mentioned as a part of the WHEN blocks of the CASE statement. MySQL CASE can also be used for conditional table updates.
CASE() Function in MySQL. CASE() function in MySQL is used to find a value by passing over conditions whenever any condition satisfies the given statement otherwise it returns the statement in an else part. However, when a condition is satisfied it stops reading further and returns the output.
If it's a scalar subquery, (i. e. you use in a SELECT
or WHERE
clause, not in FROM clause), then use this:
IF(
EXISTS
(
SELECT NULL
FROM sample_table t
WHERE t.user_id = 2
AND t.group_id = 12
), 'yes', 'no'
)
or even this:
COALESCE(
(
SELECT 'yes'
FROM sample_table t
WHERE t.user_id = 2
AND t.group_id = 12
), 'no')
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