0

Can we use IF ELSE condition inside CASE statement like below format

case when DATENAME(SECOND, GETDATE()) IN (N'Saturday', N'Sunday') 
        then if () then
              else if then 
           else 
          end,

    else 
    'Weekday'
 end
Ken White
  • 123,280
  • 14
  • 225
  • 444
vamsi
  • 13
  • 6
  • 1
    Case *expression*. [Please fix your mental model] – wildplasser Apr 16 '22 at 00:30
  • 1
    You do that with another CASE inside the outer CASE. – Ken White Apr 16 '22 at 00:38
  • The `IF` statement is a part of the procedural language PL/pgSQL. If you really want to use an `IF` statement in your logic, you need to create a function or execute an ad-hoc statement with the `DO` command. See this threat https://stackoverflow.com/a/11299968/8748450 for alternative and see this tutorial how to use `DO` https://www.postgresqltutorial.com/postgresql-plpgsql/plpgsql-if-else-statements/ – Abdul Basit Feb 22 '23 at 08:56

1 Answers1

1

We can nest CASE expressions, or use multiple tests if appropriate.
These 2 example give the same result.

select 
  x,y,
  case 
    when x = 1 then
      case when y = 1 then 11
      else 12 
      end
    when x = 2 then
      case when y = 1 then 21
      else 22
      end
  else 99 end myExression
from test;
x y myexression
1 2 12
1 1 11
2 1 21
2 2 22
null null 99
select 
  x,y,
  case
    when x = 1 and y = 1 then 11
    when x = 1 and y = 2 then 12
    when x = 2 and y = 1 then 21
    when x = 2 and y = 2 then 22
    else 99 
  end myExpression
from test;
x y myexpression
1 2 12
1 1 11
2 1 21
2 2 22
null null 99

db<>fiddle here