Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if(condition, then, else) in Oracle

MySQL/MSSQL has a neat little inline if function you can use within queries to detect null values, as shown below.

SELECT

...

foo.a_field AS "a_field",
SELECT if(foo.bar is null, 0, foo.bar) AS "bar",
foo.a_field AS "a_field",

...

The problem I'm running into now is that this code is not safe to run on an Oracle database, as it seems not to support this inline if syntax.

Is there an equivalent in Oracle?

like image 934
ModeEngage Avatar asked Sep 15 '09 16:09

ModeEngage


People also ask

Which statement will have function like IF-THEN-ELSE and they are alternative?

IF-THEN-ELSIF Statement. The IF-THEN-ELSIF statement is mainly used where one alternative should be chosen from a set of alternatives, where each alternative has its own conditions to be satisfied.

What is if else in PLSQL?

PL/SQL IF THEN ELSE statementIf the condition evaluates to TRUE, then the statements between THEN and ELSE execute. In case the condition evaluates to FALSE or NULL, the else_statements between ELSE and END IF executes.

How many else clauses can an if statement in PLSQL have?

An IF statement can have any number of ELSIF clauses; the final ELSE clause is optional. Boolean expressions are evaluated one by one from top to bottom. If any expression returns TRUE , its associated sequence of statements is executed and control passes to the next statement.

Can we use in operator in if condition in Oracle?

Yes, you can.


1 Answers

To supplement the rest of the answers here, which deal primarily with NULL values and COALESCE/NVL/NVL2:

SELECT *
FROM TheTable
WHERE field1 = CASE field2 WHEN 0 THEN 'abc' WHEN 1 THEN 'def' ELSE '' END

CASE statements are not as succinct, obviously, but they are geared towards flexibility. This is particularly useful when your conditions are not based on NULL-ness.

like image 195
David Andres Avatar answered Oct 12 '22 23:10

David Andres