Decode and Case functions (Oracle)

Asked By 110 points N/A Posted on -
qa-featured

Hi,

I have been working on Oracle for quite sometime now. I have always used the DECODE function that represents IF-THEN-ELSE clause. I read somewhere that from Oracle 8i onwards CASE statement has been introduced to get the same result. But which one out of the two is better considering both are used to do the same task?

 

SHARE
Best Answer by DiyaSharma
Best Answer
Best Answer
Answered By 0 points N/A #89175

Decode and Case functions (Oracle)

qa-featured

You are right when you say that both DECODE and CASE achieve the same functionality. But then there are certain situations where CASE is better than DECODE. It is cleaner as in easier to read and comprehend. Consider the following syntax to understand.

(case when obj='VIEW' then 1
      when obj='PROCEDURE' then 1
      else 0)
 
A similar query using DECODE would look something like this.
 
Decode( obj, 'VIEW', 1, 'PROCEDURE', 1, 0 ) 
Answered By 110 points N/A #89176

Decode and Case functions (Oracle)

qa-featured

Thanks for your inputs. Yesterday while comparing DECODE and CASE at one point I found that DECODE is better than CASE. Consider the following snippet:

Select
Case when null=null then 'true' else 'false' end from dual ;
 
Select
Decode(null,null,'true','false') from dual ;
 
The output from the first statement is: False
 
From second statement : true
Answered By 0 points N/A #89177

Decode and Case functions (Oracle)

qa-featured

Nice observation. You can equate nulls in DECODE but not in CASE. But there is a work around by which you can get the same result. When you use IS NULL instead of =NULL you get the same result with CASE. Check the following query :

Select
Case when null is null then 'true' else 'false' end from dual ;
Answered By 110 points N/A #89178

Decode and Case functions (Oracle)

qa-featured

The case syntax includes ELSE clause, is there any ELSE clause for DECODE statement?

Answered By 0 points N/A #89179

Decode and Case functions (Oracle)

qa-featured

No. DECODE doesn't have an ELSE clause. Its syntax is:

DECODE(expression,search,result[,search,result]…..[,default])

Login/Register to Answer

Related Questions