TransWikia.com

Avoid multiple Case When - MySQL

Database Administrators Asked by Binod Kalathil on December 15, 2021

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?

One 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

Answered by nbk on December 15, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP