Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if-elseif-else 'condition' in oracle SQL [duplicate]

Tags:

sql

oracle

I am wondering if there if possibility to achieve some thing like

'if-elseif-else' condition , i know there is a 'case-when-then-else' but it checks only one condition at a time (if i understand it correctly). How can i achieve if-elseif-else scenario in Oracle sql

like image 718
user964147 Avatar asked Feb 22 '13 10:02

user964147


People also ask

How do I write if else condition in Oracle?

Syntax (IF-THEN-ELSIF-ELSE) The syntax for IF-THEN-ELSIF-ELSE in Oracle/PLSQL is: IF condition1 THEN {... statements to execute when condition1 is TRUE...}

Can we use if else in Oracle SQL query?

It is always legal in PL/SQL programming to nest the IF-ELSE statements, which means you can use one IF or ELSE IF statement inside another IF or ELSE IF statement(s).

What does != Mean in Oracle?

It (<>) is a function that is used to compare values in database table. != (Not equal to) functions the same as the <> (Not equal to) comparison operator.


2 Answers

You can use if/else using case statements like this.

SELECT ename, CASE WHEN sal = 1000 THEN 'Minimum wage'
                   WHEN sal > 1000 THEN 'Over paid'
                   ELSE 'Under paid'
              END AS "Salary Status"
FROM   emp;
like image 145
ZKK Avatar answered Oct 07 '22 19:10

ZKK


i know there is a 'case-when-then-else' but it checks only one condition at a time

What you are describing is a SIMPLE case. Oracle has two case types: SIMPLE and SEARCHED (see here for more info http://docs.oracle.com/cd/B19306_01/server.102/b14200/expressions004.htm)

SIMPLE

case A
  when 1 then 'foo'
  when 2 then 'bar'
  else ..
end

SEARCHED

case
  when A=1 and B='A' then 'foo'
  when D + C =1 and B !='A' then 'Bar'
  else ..
end

you probably want to use a searched case. You can use them in PL/SQL or SQL. eg in SQL

select ..
  from table
 where case
         when A=1 and B='A' then 'foo'
         when D + C =1 and B !='A' then 'Bar'
         else ..
       end = 'foo'
like image 20
DazzaL Avatar answered Oct 07 '22 21:10

DazzaL