Search code examples
sqlpostgresqlconditional-statementscase-when

How can I use consecutive conditional clause in SQL?


I was trying to work with CASE WHEN in Postgresql in order to evaluate something and then do another thing. However, I need not only to check two things but they must be checked in consecutive order.

Example, let's say I have 3 columns: col1, col2 and col3. I want to check first if col1 is greater than 0. After checking this I want to check if col2 is greater than 0. If that's the case, I will create another column which will be the sum of all of them. However, I can't do this:

select case when col1>0 and col2>0 then col1+col2+col3 end as...

I need to do something like this:

select case when col1>0 then (case when col2>0 then col1+col2+col3) else NULL end as...

But that doesn't work. So, what can I do?


Solution

  • You were close. You can do:

    select 
      case when col1 > 0 then case when col2 > 0 then col1 + col2 + col3 end
           else NULL end as my_column1
    

    You had missed the inner end.

    By the way, a CASE expression evaluates to NULL when no when clause is matched. Therefore, else NULL is redundant.