Escolar Documentos
Profissional Documentos
Cultura Documentos
Skype: Chandra.byna
Mobile:+91
9632266314
CASE and DECODE are the two widely used constructs in the SQL . And both have
the functionality of an IF-THEN-ELSE statement to return some specified value
meeting some criteria. Even though they are used interchangeably there are some
differences between them.
This article tries to show list the advantage of CASE over DECODE and also explain
how to convert DECODE to CASE and vice versa.
CASE was introduced in Oracle 8.1.6 as a replacement for the DECODE . Anyway it
is much better option than DECODE as it is ,
1.
2.
3.
4.
Here CASE checks the value of Expression and returns the result each time for each
record as specified. Here is one such example to list the new salaries for all
employees
CASE [ expression ]
WHEN Value_1 THEN result_1
WHEN Value_2 THEN result_2
...
WHEN Value_n THEN result_n
[ELSE else_result]
END
Decode:
Page
Ebiz Technics
Skype: Chandra.byna
Mobile:+91
9632266314
The value returned, if expression is equal to search.
default
Optional. If no matches are found, the DECODE function will return default. If default
is omitted, then the DECODE function will return null (if no matches are found).
CASE Code :
SQL> SELECT EMPNO,JOB , SAL ,
CASE JOB WHEN 'ANALYST' THEN SAL*1.2
WHEN 'MANAGER' THEN SAL*1.4
ELSE SAL END NEWSAL
FROM EMP;
The Equivalent DECODE syntax will be
DECODE Code :
SQL> SELECT EMPNO,JOB , SAL ,
DECODE (JOB,'ANALYST', SAL*1.2 ,
'MANAGER', SAL*1.4,
SAL ) NEWSAL
FROM EMP;
Here CASE tries to return the values on meeting some conditions rather than
checking for the expressions . Here is such an example with the same functionality
as above .
Though both CASE and DECODE are used interchangeably , CASE is definitely
proved to be better and elegant option over DECODE as it is more flexible , readable
and ANSI Compatible . And moreover CASE is preferred in PL/SQL statements as
DECODE is only supported in the SQL statements.
Performance tips
ebizTechnics
Page
Code :
Ebiz Technics
Skype: Chandra.byna
Mobile:+91
9632266314
FROM emp WHERE sal < 2000;
SELECT COUNT ( * )
FROM emp
WHERE sal BETWEEN 2000 AND 4000;
SELECT COUNT ( * )
FROM emp
WHERE sal > 4000;
However, it is more efficient to run the entire query in a single statement. Each
number is calculated as one column. The count uses a filter with the CASE
statement to count only the rows where the condition is valid. For example:
Page
SELECT COUNT (CASE WHEN sal < 2000 THEN 1 ELSE NULL END) count1,
COUNT (CASE WHEN sal BETWEEN 2001 AND 4000 THEN 1 ELSE NULL END)
count2,
COUNT (CASE WHEN sal > 4000 THEN 1 ELSE NULL END) count3
FROM emp;
ebizTechnics