Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CASE Statement in where clause using equal to and IN

WHERE CONDITION1='ABC'
AND Status =
    CASE  @Option 
            WHEN 1 THEN 'True'
            WHEN 2 THEN 'False'
            WHEN 3 THEN  NULL
            WHEn 4 THEN **IN ('True', 'False', NULL)**
    END

How do I write a query where my first options match directly using = but my last option needs an IN

The above query gives error, but I want something similar to it, which I am not able to find out.

like image 200
user1820973 Avatar asked Feb 01 '26 08:02

user1820973


1 Answers

A CASE statement can't return a set of values... but this query should give you the same results:

WHERE CONDITION1='ABC'
AND Status =
    CASE  
        WHEN 1 THEN 'True'
        WHEN 2 THEN 'False'
        WHEN 3 THEN NULL
        WHEN 4 THEN Status
    END

Also, note that unless you have ANSI_NULLS OFF, Status will never = NULL... you would need to use IS NULL for this comparison, and you'd need to forgo the CASE statement altogether.

like image 81
Michael Fredrickson Avatar answered Feb 03 '26 22:02

Michael Fredrickson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!