Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling empty set in MySQL CASE statement

Tags:

null

mysql

case

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?

like image 931
Rich Churcher Avatar asked Aug 20 '09 14:08

Rich Churcher


People also ask

Is null in case statement MySQL?

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.

What is empty set in MySQL?

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.

Can we use CASE statement in MySQL?

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.

What is the use of case in MySQL?

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.


1 Answers

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')
like image 59
Quassnoi Avatar answered Sep 28 '22 03:09

Quassnoi