Avoid multiple Case When – MySQL

Posted on

Question :

I have a query:

Select <CASE WHEN>, myfunction(param1, <CASE WHEN>)
FROM table

Both the Case When instances are the same set of conditions. So here I am clearly repeating the same conditions.

Question: Is there a way to not repeat the same Case When block efficiently?

Answer :

For this you can use user defined Varaible

Select @res := CASE WHEN A = 1 then a END, myfunction(param1, @res)
FROM table1;

Or in mysql 8

WITH myselectanswer as
(Select  CASE WHEN A = 1 then a END myresult
FROM table1)
Select myselectanswer.myresult, myfunction(param1, myselectanswer.myresult)
FROM myselectanswer

Leave a Reply

Your email address will not be published. Required fields are marked *