Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use CASE without ELSE in WHERE clause like IF

Is it possible to use a CASE without ELSE in WHERE clause like an IF? for put a condition or not.

Example

WHERE monto = 100
    AND CASE WHEN @canal is not null
        THEN canal = @canal
    END

I ask this because I want to do this

WHERE monto = 100
    IF (@canal is not null){
        AND canal = @canal
    }
like image 522
Felipe Pincheira Avatar asked Nov 22 '25 17:11

Felipe Pincheira


1 Answers

You need to include this condition in the WHERE:

WHERE monto = 100 AND ( @canal IS NULL OR canal = @canal )

If it's actually in a stored-procedure it might be more efficient if you use an IF...ELSE around the different queries, one with this parameter and one without.

like image 172
Tim Schmelter Avatar answered Nov 25 '25 06:11

Tim Schmelter