Another oracle sql statement that you may need in order to simplify and optimize your code is the use of CASE statement. Here’s how it is being used.

Syntax #1


CASE [ expression ]
WHEN condition_1 THEN result_1
WHEN condition_2 THEN result_2
...
WHEN condition_n THEN result_n
ELSE result
END

Example


SELECT last_name, commission_pct,
(CASE commission_pct
WHEN 0.1 THEN ‘Low’
WHEN 0.15 THEN ‘Average’
WHEN 0.2 THEN ‘High’
ELSE ‘N/A’
END ) Commission
FROM employees ORDER BY last_name;

Syntax #2


CASE
WHEN [ condition_1 ] THEN result_1
WHEN [ condition_2 ] THEN result_2
...
WHEN [ condition_n ] THEN result_n
ELSE result
END

Example


SELECT m.paper_type ,
m.paper_brand ,
m.paper_grammage,
m.paper_width ,
m.paper_length ,
m.paper_stock_no,
(
CASE
WHEN NVL(smc.qty_reserved_onhand,0) != NVL(st.sum_qty_r_oh,0) THEN 'QROH NOT TALLY'
WHEN NVL(smc.qty_reserved_incom,0) != NVL(st.sum_qty_r_incom,0) THEN 'QRINC NOT TALLY'
WHEN NVL(smc.ton_reserved_onhand,0) != NVL(st.sum_ton_r_oh,0) THEN 'TROH NOT TALLY'
WHEN NVL(smc.ton_reserved_incom,0) != NVL(st.sum_ton_r_incom,0) THEN 'TRINC NOT TALLY'
END
) ERROR_MESSAGE
from paper_stock_master m

Personally, I use Syntax #2 most of the time. I don’t know why but maybe it just happened that I find it more suitable to use in the situations that I needed the CASE statement.

Difference Between DECODE and CASE WHEN

The most fundamental difference between the two oracle statements is that in DECODE, you are comparing a field or value in a given set of values or fields. It’s actually a shorthand for IF..ELSIF..ELSE statement with the condition all set to equals (=). CASE WHEN is almost the same but you can use any conditional operator (i.e, =,!=, >, >= , <, <=, etc) thereby giving you more freedom and flexibility in writing your code.

In may instances CASE WHEN helped me reduce the number of lines of my codes as well as optimize the performance. On top of that, I no longer need a full pl/sql program with multiple queries and even cursors to be able to provide the result that a simple CASE statement can provide. However CASE, like any other sql commands, is only applicable for certain scenarios. It’s not a magic keyword that will solve/apply to everything. So you have to weigh your options if you need it or not.

Ciao!

Comments are closed.

Post Navigation