My work as an Analyst in a digital company involves querying on a daily basis. Now, the different stakeholders often come with a lot of weird requests where I have to group some attributes together (ex: user 1, 2 and 3 should be under Group A or campaign a,b and c should be grouped together under Campaign ABC etc.)
Now, I understand that I can create a lookup table and map these using a join but since the grouping changes very often, I usually use a case when expression. During all this time, I was writing my case when the following way:
CASE WHEN user_id in (1,2,3) THEN 'Group A' ELSE
CASE WHEN user_id in (4,5,6) THEN 'Group B' ELSE
CASE WHEN user_id in (7,8,9) THEN 'Group C' ELSE'N/A' END END END AS grouped_users
This often made my code not readable because formatting the code would cascade the case expressions and they'd often be far to the right.
Today I just learned, by accident, that the right way to do this is:
CASE
WHEN user_id in (1,2,3) THEN 'Group A'
WHEN user_id in (4,5,6) THEN 'Group B'
WHEN user_id in (7,8,9) THEN 'Group C'
ELSE 'N/A' END as grouped_users
I'm amazed how clear this is. Maybe my programming background intuitively made me this about this like:
if {
} else if {
} else if {
} else {
}
I never thought about this because this is not a switch case expression that goes like
CASE user_id
WHEN 1 THEN 'Group A'
WHEN 3 THEN 'Group B'
ELSE 0 END as grouped_users
This is just a normal case expression without the need the nest other case expressions for other conditions.
As someone who is a fan of nesting many sub-queries, CTEs and joining sub-queries to each other, I have absolutely no idea about how I missed this simple concept. I've been nesting cases all this time and I don't know if I can get over it. Tell me r/SQL , did something similar ever happen to you ?
EDIT: Forgot to mention that not only this way of writing the statement is more appealing but I tested it on a query with more than 15 nested cases and it was executed 2 times faster.