196

I'm writing an SQL Query, where a few of the columns returned need to be calculated depending on quite a lot of conditions.

I'm currently using nested case statements, but its getting messy. Is there a better (more organised and/or readable) way?

(I am using Microsoft SQL Server, 2005)


A simplified example:

SELECT
    col1,
    col2,
    col3,
    CASE
        WHEN condition 
        THEN
            CASE
                WHEN condition1 
                THEN
                    CASE 
                        WHEN condition2
                        THEN calculation1
                        ELSE calculation2
                    END
                ELSE
                    CASE 
                        WHEN condition2
                        THEN calculation3
                        ELSE calculation4
                    END
            END
        ELSE 
            CASE 
                WHEN condition1 
                THEN 
                    CASE
                        WHEN condition2 
                        THEN calculation5
                        ELSE calculation6
                    END
                ELSE
                    CASE
                        WHEN condition2 
                        THEN calculation7
                        ELSE calculation8
                    END
            END            
    END AS 'calculatedcol1',
    col4,
    col5 -- etc
FROM table
Flimzy
  • 60,850
  • 13
  • 104
  • 147
Sophia
  • 5,253
  • 9
  • 35
  • 43
  • Hi, did you use a tool (like SQLinForm) to indent the nested queries so nicely? – Guido Jun 01 '13 at 13:20
  • 1
    Appreciate you teaching me a nicer formatting method for nested `CASE WHEN` – Simon1979 Jan 08 '15 at 06:39
  • There are certainly times when this would be efficient and helpful, but in general, I like to keep logic away from my SQL queries. Just a tip for posterity. – tschwab Jul 13 '18 at 19:50

9 Answers9

203

You could try some sort of COALESCE trick, eg:

SELECT COALESCE(
  CASE WHEN condition1 THEN calculation1 ELSE NULL END,
  CASE WHEN condition2 THEN calculation2 ELSE NULL END,
  etc...
)
Chris KL
  • 4,568
  • 3
  • 24
  • 33
  • Nice, I just tested to ensure that it short-circuits, and was suprised to find that it does. So if condition1 checked for a divide by zero, it appears that it's safe to do it in condition2. Not sure if this is guaranteed. – Cade Roux Feb 03 '09 at 03:34
  • 14
    One catch is that if one of your cases legitimately wants to return a NULL, it's no longer possible. – Chris KL Feb 05 '09 at 03:56
  • 10
    This is a great trick, but keep in mind that it may not perform as well as using CASE statements alone. This is "documented" in the Community Additions section here - http://msdn.microsoft.com/en-us/library/ms190349.aspx. My DBA just put the hammer down when I implemented this solution... – shanabus Jan 25 '13 at 16:54
  • When is this better than just a case statement (@beach's answer)? – Ronnie Overby Apr 04 '14 at 17:28
  • How to rename a column in this answer.. e.g if I want to rename 'calculation1' to 'CAL1'... How is it possible syntactically ? – Renascent Apr 12 '17 at 06:38
  • While it is a nice trick, since it does not appear to short-circuit (ref: https://stackoverflow.com/a/506033/3358272), I'd think this would be far less efficient, running numerous `CASE` statements that will not be used. – r2evans Feb 20 '20 at 17:56
  • this would return null when condition1 is not true... at least it did for me – Bob Sheehan Mar 03 '20 at 15:28
96

Wrap all those cases into one.


SELECT
    col1,
    col2,
    col3,
    CASE
        WHEN condition1 THEN calculation1 
        WHEN condition2 THEN calculation2
        WHEN condition3 THEN calculation3
        WHEN condition4 THEN calculation4
        WHEN condition5 THEN calculation5
        ELSE NULL         
    END AS 'calculatedcol1',
    col4,
    col5 -- etc
FROM table
Deejers
  • 2,419
  • 1
  • 20
  • 17
36

You can combine multiple conditions to avoid the situation:

CASE WHEN condition1 = true AND condition2 = true THEN calculation1 
     WHEN condition1 = true AND condition2 = false 
     ELSE 'what so ever' END,
ssingh
  • 453
  • 5
  • 14
26

I personally do it this way, keeping the embedded CASE expressions confined. I'd also put comments in to explain what is going on. If it is too complex, break it out into function.

SELECT
    col1,
    col2,
    col3,
    CASE WHEN condition THEN
      CASE WHEN condition1 THEN
        CASE WHEN condition2 THEN calculation1
        ELSE calculation2 END
      ELSE
        CASE WHEN condition2 THEN calculation3
        ELSE calculation4 END
      END
    ELSE CASE WHEN condition1 THEN 
      CASE WHEN condition2 THEN calculation5
      ELSE calculation6 END
    ELSE CASE WHEN condition2 THEN calculation7
         ELSE calculation8 END
    END AS 'calculatedcol1',
    col4,
    col5 -- etc
FROM table
beach
  • 7,556
  • 3
  • 27
  • 25
10

Here's a simple solution to the nested "Complex" case statment: --Nested Case Complex Expression

select  datediff(dd,Invdate,'2009/01/31')+1 as DaysOld, 
    case when datediff(dd,Invdate,'2009/01/31')+1 >150 then 6 else
        case when datediff(dd,Invdate,'2009/01/31')+1 >120 then 5 else 
            case when datediff(dd,Invdate,'2009/01/31')+1 >90 then 4 else 
                case when datediff(dd,Invdate,'2009/01/31')+1 >60 then 3 else 
                    case when datediff(dd,Invdate,'2009/01/31')+1 >30 then 2 else 
                        case when datediff(dd,Invdate,'2009/01/31')+1 >30 then 1 end 
                    end
                end
            end
        end
    end as Bucket
from rm20090131atb

Just make sure you have an end statement for every case statement

Termato
  • 1,458
  • 16
  • 33
6

We can combine multiple conditions together to reduce the performance overhead.

Let there are three variables a b c on which we want to perform cases. We can do this as below:

CASE WHEN a = 1 AND b = 1 AND c = 1 THEN '1'
     WHEN a = 0 AND b = 0 AND c = 1 THEN '0'
ELSE '0' END,
Sanjeev Singh
  • 3,690
  • 2
  • 29
  • 38
5

a user-defined function may server better, at least to hide the logic - esp. if you need to do this in more than one query

Steven A. Lowe
  • 58,325
  • 18
  • 127
  • 199
2

I went through this and found all the answers super cool, however wants to add to answer given by @deejers

    SELECT
    col1,
    col2,
    col3,
    CASE
        WHEN condition1 THEN calculation1 
        WHEN condition2 THEN calculation2
        WHEN condition3 THEN calculation3
        WHEN condition4 THEN calculation4
        WHEN condition5 THEN calculation5         
    END AS 'calculatedcol1',
    col4,
    col5 -- etc
FROM table

you can make ELSE optional as its not mandatory, it is very helpful in many scenarios.

user3065757
  • 374
  • 1
  • 4
  • 12
0

This example might help you, the picture shows how SQL case statement will look like when there are if and more than one inner if loops

enter image description here

Sandy
  • 133
  • 1
  • 1
  • 8
  • 1
    Please put the text of the code instead of screenshots because screenshots are hard to reuse or confirm. – Manik Feb 04 '21 at 10:16