Case or Decode ?
Oracle 11.2.3.0
Ok, here is the situation. on a view, there is a column called 'DUE_DATE'. What I want to do is via some logic (using case or decode I presume) depending on how many days there is between sysdate (todays date) and the DUE_DATE. to output a value .. So as an example, what I mean is if the amount of days from sysdate to the DUE_DATE is lets say, 20 days, one the report, I was it to say "1-30d"..
Todays date= due date + 1 to 30days = “1-30d”
Todays date= due date + 31 to 60days = “31-60d”
Todays date= due date + 61 to 90days = “61-90d”
Todays date= due date +>90days =”>90d”
How can I achieve this.. Any help, assistance would be greatly appreciated.
Hi,
Here's one way
CASE
WHEN due_date < SYSDATE - 90 THEN '>90d'
WHEN due_date < SYSDATE - 60 THEN '61-90d'
WHEN due_date < SYSDATE - 30 THEN '31-60d'
WHEN due_date < SYSDATE - 1 THEN '1-30d'
ELSE NULL -- or whatever
END
Depending on your requirements, you may want to use TRUNC (SYSDATE) wherever I used SYSDATE above.
ELSE NULL is the default. If you want the expression to return NULL when due_date is later than SYSDATE - 1 (or when due_date is NULL) then you can leave out the ELSE clause.
Similar Messages
-
Case or decode in select statement for comparison
Hi,
How can I do a comparison
like
if sal < 50, output 1.1 * comm
if sal > 50 and < = 100 output 1.2 * comm
else output comm
in a single select statement.
I tried using case and decode but I am not sure how to use it in comparison operations.
Please helpuse the 'case' construct:
SELECT
NORMAL_FIELD
, (CASE
WHEN (SAL < 50) THEN 1.1 * COMM
WHEN (SAL > 50) AND (SAL <= 100) THEN 1.2 * COMM
ELSE COMM
END
) AS CALCULATED_COMM
FROM
TB_xxxx
WHERE xxxx
hope this helps -
How to use case and decode to extract the data
Hello PL/SQL Gurus,
I am using Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production version
I have a table in following format -
drop table TT2;
create table TT2(College, Class,gender,status,fees) as select
'IITB','MBA','M','P',255600 from dual union all select
'IITK','MTech','M','P',300000 from dual union all select
'IITD','MBA','F','P',450000 from dual union all select
'IITKH','MBA','F','P',350000 from dual union all select
'IITC','MTech','F','P',420000 from dual union all select
'IITB','MTech','M','P',185000 from dual union all select
'IITC','MTech','M','P',235000 from dual union all select
'IITD','MBA','F','F',175000 from dual union all select
'IITM','MBA','M','F',257000 from dual union all select
'IITKH','MTech','F','P',335000 from dual union all select
'IITD','MBA','F','P',540335 from dual union all select
'IITC','MBA','F','F',125089 from dual union all select
'IITD','MTech','M','P',290756 from dual union all select
'IITM','MBA','M','P',200000 from dual union all select
'IITKH','MBA','F','F',534990 from dual union all select
'IITD','MBA','F','P',221000 from dual ;some of the extraction conditions are as following -
CASE CONDITION
College in 'IITB' and status='P'- 'WestRegion Passed'
College in 'IITC' and status='P'- 'SouthRegion Passed'
College in 'IITD' and 'IITK' and status='P' and Gender='F' - 'NothRegion Female Passed'
College not in 'IITK' and status='F' - 'Ex Kanpur Failed'
Expected output -
Region Statnding Fees
WestRegion Passed 440460
SouthRegion Passed 655000
NothRegion Female Passed 1386335
Ex Kanpur Failed 1092079SQL Used
I am using the following query which only make sure of case but this is not how i want the output , if i try to use the case within decode then how to work on this -
SELECT (CASE WHEN College in ('IITB') and status='P' then sum(fees) else 0 end) WP,
(case when College in ('IITC') and status='P' then sum(fees) else 0 end) SP,
(case when College in ('IITD','IITK') and gender='F' and status='P' then sum(fees) else 0 end) NFP,
(case when College in ('IITK') and status='F' then sum(fees) else 0 end) ExKF
FROM
TT2
GROUP BY College, Class,gender,statususer555994 wrote:
Thank you so much jeneesh i am really thankful to you ...vov.
one more query in case if any of the selection don't have the output data , then values will be displayed like -One way..
with t as
--"Add all your descriptions
(select 'WestRegion Passed' region_standing from dual union all
select 'SouthRegion Passed' region_standing from dual union all
select 'NothRegion Female Passed' region_standing from dual union all
select 'Ex Kanpur Failed' region_standing from dual)
select region_standing,sum(fees) fees
from (
(SELECT CASE WHEN College in ('IITB') and status='P'
then 'WestRegion Passed'
when College in ('IITC') and status='P'
then 'SouthRegion Passed'
when College in ('IITD','IITK') and gender='F' and status='P'
then 'NothRegion Female Passed'
when College in ('IITK') and status='F'
then 'Ex Kanpur Failed'
else 'Others' end region_standing,
sum(fees) fees
FROM TT2
GROUP BY CASE WHEN College in ('IITB') and status='P'
then 'WestRegion Passed'
when College in ('IITC') and status='P'
then 'SouthRegion Passed'
when College in ('IITD','IITK') and gender='F' and status='P'
then 'NothRegion Female Passed'
when College in ('IITK') and status='F'
then 'Ex Kanpur Failed'
else 'Others' end
union all
select region_standing,0
from t
group by region_standing;
REGION_STANDING FEES
Others 2567835
NothRegion Female Passed 1211335
WestRegion Passed 440600
Ex Kanpur Failed 0
SouthRegion Passed 655000
{code}
Edited by: jeneesh on Nov 5, 2012 5:07 PM -
Which is faster while executing statment having Case or Decode.
Pls tell me which execute faster a case or decode.
ajallen wrote:
If you are really concerned about this, then you are being taken over by the tuning virus. You are out of control. You are tuning beyond reason. DECODE() is deprecated - not being enhanced. CASE is the new preferred approach. CASE is simpler and easier to code/follow.I can't find a link saying that DECODE() function is already deprecated. Can you give us a valid link?
Regards. -
What is the Optional(other than Case or Decode)
Hi friends,
i need to refer an image to the corresponding blob content in my report for each and every row. i tried with case or decode but it is helpless as the case and decode does not support BLOB format, instead what is the other optional i can use inorder to solve the problem
SELECT
decode(attachment,(select attachment from it_issues where lower(name) like '%txt%') ,
'<img src="#WORKSPACE_IMAGES#Notepad.jpg">',
(select attachment from it_issues where lower(name) like '%pdf%'),
'<img src="#WORKSPACE_IMAGES#Adobe pdf.bmp">',
(select attachment from it_issues where lower(name) like '%xls%'),
'<img src="#WORKSPACE_IMAGES#Excel.png">',
(select attachment from it_issues where lower(name) like '%html%'),
'<img src="#WORKSPACE_IMAGES#Html.bmp">',
(select attachment from it_issues where lower(name) like '%sql%'),
'<img src="#WORKSPACE_IMAGES#Notepad.jpg">',
(select attachment from it_issues where lower(name) like '%ppt%'),
'<img src="#WORKSPACE_IMAGES#powerpoint.jpg">',
(select attachment from it_issues where lower(name) like '%zip%'),
'<img src="#WORKSPACE_IMAGES#rar 02.bmp">',
(select attachment from it_issues where lower(name) like '%doc%'),
'<img src="#WORKSPACE_IMAGES#word.bmp">', null) Attachment
FROM it_issuesAbove is My code which is not sufficient to use, any replacement to it.. It will be very helpful for me
Regards,
MiniHi metzguar,
Thanks for the reply my image is stored in the attachment column but that image name is stored in filename column in my table, so i cannot refer attachment = txt, because the image name(txt)is stored in another column filename.
But i need to show the image icon in my attachment column where the image is storing. That is the problem for me.
Thanks
Regards,
Mini -
I have a table with say a column named “COLOR” with 500 different values - lets say 3 of the values are red white and blue. There are 497 others
I want insert from table with the color column into another table named "OTHER"
But everytime I hit a blue, I want to insert red instead. All the other values stay the same as they are.
I've tried CASE and DECODE but it leaves me with nulls for the other 497 values. Is there a way to do this by saying only when I hit the blue, I want it to be red, without hardcoding all the other values? For example:
Insert into OTHER table
Select
COLUMN1,
COLUMN2,
COLUMN3,
COLOR (If color is blue, insert red – then let all other colors be what they are)
COLUMN5Hi,
Sure, use an ELSE clause:
CASE
WHEN color = 'blue' THEN 'red'
ELSE color
ENDor, if you prefer DECODE, pass an even number of arguments:
DECODE ( color
, 'blue' , 'red'
, color
)Either way, the expression returns 'red' when color is 'blue', and returns color itself in all other cases. -
CASE or DECODE - what is faster?
when i use them in select clause with varchar2 or number datatype? (Oracle 10.2 EE)
regardsHi,
This helped me in understanding the difference between case and decode
Quoting from an expert amoungst experts Billy Verreynne. here is what he says:
From what i know, in case of multiple condition checking, Case is simpler to write when compared to Decode. Also Decode can not be used in PL/SQL code where as CASE is possible.
There is very little performance difference between CASE and DECODE on the same platform. One has to run 100's of 1000's of iterations to see a difference, and even then it is debatable of whether that difference is just due to the CASE vs DECODE.
There seems to be a difference in performance between CASE and DECODE depending on the type of CPU. On some CPU architecture a DECODE will seem to be just slightly faster. On others, the CASE will seem to be slightly faster.
The performance difference is so slight that it makes very little sense in using that as primary criteria for whether to use CASE or DECODE. So unless you're calling this statement from a very tight loop doing millions of iterations, the decision should rather be which one, CASE or DECODE, best suits the need.
Wrong question really.. unless you writing a very tight loop doing 100's of 1000's of iterations using that type of conditional structure. And even then performance difference will not be that significant.
The right question to ask is which one is more flexible and allows for the programmer that comes after you to read and understand and maintain your code. The CASE statement is in this regard, a lot better than a DECODE statement.
Looking just at performance (which I suggest you do not do in isolation!!), I get mixed results using 10G Enterprise on different platforms (HP-UX vs SUN AMD) and operating systems (HP-UX vs Linux).
On the former the DECODE is slightly faster. On the latter the CASE is slightly faster.
Using the construct you've specified and doing a tight loop of a 100,000 iterations, the elapsed execution times are:
HP-UX DECODE = 00:00:11.83
HP-UX CASE = 00:00:12.32
Linux/AMD DECODE =00:00:02.02
Linux/AMD CASE = 00:00:01.84
Obviosuly the CPU architecture plays a major role here. The AMD is considered as the best 64 CPU on the market. The HP-UX PARISC CPU (also 64bit), does not really compare raw performance wise. In addition this is a RISC CPU whereas the AMD CPU is I believe more CISC than RISC.
Also interesting that the faster Sun AMD/Linux server I used for this benchmark is about 10% the price of the HP-UX server.. and about 5x faster ito raw speed as this benchmark showed. :-)
An interesting exercise, but one with little real world value. Yes performance is important. But within PL/SQL, not to the level about debating whether a CASE or DECODE is faster. As I've mentioned, I believe the right question being one about readability and maintenance and not performance in this case.
Hope this helps and all credit goes to the expert billy.
Edited by: Kevin CK on Aug 5, 2010 4:07 PM
Edited by: Kevin CK on Aug 5, 2010 4:08 PM -
Difference between CASE and DECODE
Hi All,
Could you please explain me the basic differences between the CASE and DECODE, which performs fast...?
DECODE is Oracle one, and the CASE is ANSI standard.
As per my knowledge, CASE is a statement and DECODE is a function which was defined in the Standard package.
If we use DECODE, the package has to load first, so it will take a little longer than the CASE. CASE is a simple statement which is ANSI standard.
We can use the CASE in the where clause and can not use the DECODE in the where clause.
Please clarify me and correct me if anything wrong.
Thanks,IMO, the main important point is the way CASE and DECODE handles NULL
SQL> select ename,comm,
2 decode(comm,300,'A',null,'B','C') dcd,
3 case comm when 300 then 'A'
4 when null then 'B'
5 else 'C'
6 end cs
7 from emp;
ENAME COMM D C
SMITH B C --"DECODE treats NULL=NULL. But for CASE, NULL is not equal to "another" NULL
ALLEN 300 A A
WARD 500 C C
JONES B C
MARTIN 1400 C C
BLAKE B C
CLARK B C
SCOTT B C
KING B C
TURNER 0 C C
ADAMS B C
JAMES B C
FORD B C
MILLER B C
14 rows selected.
{code}
Edited by: jeneesh on Jun 3, 2013 1:13 PM
Note: in CASE, you should use IS NULL
{code}
case when comm=300 then 'A'
when comm is null then 'B'
else 'C'
end
{code} -
CASE vs DECODE - CASE with SUM and All in Page Item is non aggregable
Hi,
I'm using Discoverer 9.0.4.
After switching calculations from DECODE to CASE
I found out that case gives a non aggregable result when using a Page Item and selecting <All>.
The calculations
(SUM x) / (SUM y)
or
(x SUM) / (y SUM)
where x and y are variables, work fine with page item <All>.
But for example:
CASE WHEN 1=2 THEN 1 ELSE (SUM x) / (SUM y) END
gives non-aggregable.
The same code works with DECODE:
DECODE(1,2,1,(SUM x) / (SUM y))
and is aggregable.
Does anyone know a reason or a way to make it work with CASE?
Thanks,
Joao Noronha
P.S.: I wanted <= comparisons and CASE is the best in simplicity,
but now I know I can do it with DECODE, still looking ok using LEAST instead of ABS of the difference.Hi there
I think therefore you have answered your own question and determined that using CASE in aggregations is not a good idea. I only threw out the two CASE options as ideas not as solutions, just in case (pardon the pun) one of these worked in your situation.
Your comment I must say that if it worked it would give a wrong result (the sum of the divisions is not the same as the division of the sums) may give the wrong answer in your case but may be correct in others. It just depends how the items in the folder have been set up. I agree though that SUM(x) / SUM(y) will more often than not give the right answer.
This discussion about DECODE vs CASE has been going on ever since Oracle introduced CASE as a means of placating a younger breed of user who needed an IF..THEN...ELSE construct and could not get their minds around the intricacies of DECODE. The DECODE is a much more reliable function than CASE because it has been around for a long time allowing Oracle plenty of opportunity to iron the bugs out of it. If I get a chance I will always use a DECODE whenever aggregations are required. However, when no aggregations are in use then I'll use CASE, simply because it's easier for users to work with.
Unfortunately, users need to work with aggregations and so I don't see any alternative to Plus users having to learn DECODE. Whenever I teach Plus I always teach the users both CASE and DECODE but point out that DECODE has fewer issues that CASE. Oh, and talking of issues, try getting the THEN and ELSE components to return a different datatype. CASE has a fit and will not compile.
Best wishes and glad you got your issue solved - you did right?
Regards
Michael -
Hi,
I am running below statement.
create table test_abc
(cnt number,
outcome varchar2(20));
insert into test_abc values(1,'EXISTINGDOMFUELCUST');
insert into test_abc values(1,'Answer Phone');
insert into test_abc values(1,'Answer Phone');
insert into test_abc values(1,'Answer Phone');
insert into test_abc values(1,'Answer Phone');
insert into test_abc values(1,'Answer Phone');
commit;
Now I used case and decode
select count(*),ot from (
select (case when outcome ='EXISTINGDOMFUELCUST' then 'Existing Domestic Fuel Customer'
when outcome='Answer Phone' then 'Answer Phone'
when outcome='Answer Phone' then 'Answer Machine' end) ot
from test_abc)
group by ot;
select count(*),decode(outcome,'EXISTINGDOMFUELCUST','Existing Domestic Fuel Customer','Answer Phone',
'Answer Phone','Answer Phone','Answer Machine')
from test_abc
group by decode(outcome,'EXISTINGDOMFUELCUST','Existing Domestic Fuel Customer','Answer Phone',
'Answer Phone','Answer Phone','Answer Machine')
and getting same output
cnt ot
5 Answer Phone
1 Existing Domestic Fuel Customer
but I want output should be
cnt ot
5 Answer Phone
5 Answer Machine
1 Existing Domestic Fuel Customer
please suggestIndra Budiantho wrote:
/* Formatted on 8/28/2012 3:10:28 PM (QP5 v5.139.911.3011) */
SELECT CASE
WHEN outcome = 'EXISTINGDOMFUELCUST'
THEN
'Existing Domestic Fuel Customer'
WHEN outcome = 'Answer Phone'
THEN
'Answer Phone'
END
outcome,
COUNT (*)
FROM test_abc
GROUP BY outcome
union
SELECT CASE
WHEN outcome = 'EXISTINGDOMFUELCUST'
THEN
'Existing Domestic Fuel Customer'
WHEN outcome = 'Answer Phone'
THEN
'Answer Machine'
END
outcome,
COUNT (*)
FROM test_abc
where outcome = 'Answer Phone'
GROUP BY outcomeo/p
Answer Machine 5
Answer Phone 5
Existing Domestic Fuel Customer 1This can be simplified..
Also, UNION will unnecessarily do a distinct operation.
SELECT CASE
WHEN outcome = 'EXISTINGDOMFUELCUST'
THEN
'Existing Domestic Fuel Customer'
WHEN outcome = 'Answer Phone'
THEN
'Answer Phone'
END
outcome,
COUNT (*)
FROM test_abc
GROUP BY outcome
union all
SELECT 'Answer Machine'
outcome,
COUNT (*)
FROM test_abc
where outcome = 'Answer Phone'
GROUP BY outcome -
Regarding case and decode.
Hi !
I need to return all the employess, and indicate with "YES" or "NO" wherther they receive a commission.
I am trying to get this by using CASE and DECODE but result is comming different.
USING DECODE:
SELECT ename,
sal,
DECODE(comm,NULL,'NO',
'YES') COMM
FROM emp;
USING CASE:
SELECT ename,
sal,
CASE comm
WHEN NULL THEN 'NO'
ELSE 'YES'
END
FROM emp;
DECODE is returning actual data(comm is NO where comm is null and comm is YES where comm is not null). Where as CASE is retunring YES for all employees commission even comm is null..
I am not able to understand where I was wrong.
Can any one help me out?
Thanks
RajeshHi Rajesh,
I tried to solve your query this way, check if it serves the purpose
/***Using Decode***/
SELECT EMPLOYEE_ID, DECODE(NVL(COMMISSION_PCT, 0), 0, 'NO', 'YES')
FROM EMPLOYEES
/****Using Case***/
SELECT EMPLOYEE_ID, CASE NVL(COMMISSION_PCT, 0)
WHEN 0 THEN 'NO'
ELSE 'YES'
END CASE
FROM EMPLOYEES
/ -
Pls tell me difference between case and decode
Hi all
pls tell me difference between case and decode
regardsWell not entirely true when you consider working with
sign and decode together. Your example could be
written with decode and sign like this:
decode(sign(sal-1000),1,sal+comm,-1,sal,0)But the case expression reads more easily, I admit.Rob it was just example you considered it special case ,BTW can you do it for me by DECODE function.
SQL> SELECT sal,comm,CASE WHEN sal>1000 AND sal<1300 THEN sal+comm ELSE 0 END
2 FROM emp
3 /
SAL COMM CASEWHENSAL>1000ANDSAL<1300THENSAL+COMMELSE0END
5000 0
2850 0
2450 0
2975 0
1250 1400 2650
1600 300 0
1500 0 0
950 0
1250 500 1750
3000 0
800 0
SAL COMM CASEWHENSAL>1000ANDSAL<1300THENSAL+COMMELSE0END
3000 0
1100
1300 0
14 rows selected.Note for OP CASE can be used within PL/SQL witing ORACLE 9i or later release
but DECODE function can only be used within SQL.
Khurram -
Help on converting query with case into decode
Hi Can anyone help me to revise my plsql query? Below is a portion og the procedure I am changing to meet Oracle 8i.
SELECT SUM(NVL(CASE WHEN (weeks='wk1' ) THEN qty END, 0)) wk1,
SUM(NVL(CASE WHEN (weeks='wk2' ) THEN qty END, 0)) wk2,
SUM(NVL(CASE WHEN (weeks='wk3' ) THEN qty END, 0)) wk3,
SUM(NVL(CASE WHEN (weeks='wk4' ) THEN qty END, 0)) wk4
FROM TABLE1
Thanks in advance.pls try this....(code not tested as no create table etc provided).
select dt
from (select decode(is_tbd,
'yes',
decode(is_tbd_order,
'no',
'tbd',
decode(sign(ex_fac_date - (v_asofdate + 131)),
1,
'tbd',
null),
decode(sign(ex_fac_date - (v_asofdate + 131)),
1,
'tbd',
null)),
null) dt
from dual
union all
select decode(sign(ex_fac_date - (v_asofdate - 1)),
1,
decode(sign(ex_fac_date - (v_asofdate + 5)),
0,
decode(is_tbd, 'no', 'wk1', null),
null),
null)
from dual
union all
select decode(sign(ex_fac_date - (v_asofdate + 6)),
1,
decode(sign(ex_fac_date - (v_asofdate + 12)),
0,
decode(is_tbd, 'no', 'wk2', null),
null),
null)
from dual
select decode(sign(ex_fac_date - (v_asofdate + 13)),
1,
decode(sign(ex_fac_date - (v_asofdate + 19)),
0,
decode(is_tbd, 'no', 'wk3', null),
null),
null)
from dual
union all
select decode(sign(ex_fac_date - (v_asofdate - 1)),
0,
decode(is_tbd, 'no', 'past_due', null),
null)
from dual
where dt is not null
Regards -
can someone help me with this query
I want to display the grade of all employees based on the value of job_id column.
ex:
job_id: grade:
ad_pres a
st_man b
it_prog c
sa_rep d
st_clerk e
none of the above o
HOW IS THIS DONE USING EITHER DECODE AND CASE STAMENTS
THANKS IN ADVANCE -- 'JUST LEARNING'Hello,
I presume, there is no table connecting job_id with grade, otherwise you need no decode.
Try
SELECT DECODE(jod_id,'ad_pres','a','st_man','b',...) grade
FROM employees;
Yours
Marcus -
How to use CASE or DECODE in this?
Hi , I have a query like this
AND ...smthng
AND --smtg
AND age BETWEEN ....For the last AND clause for age column, I have the values passed from IN param of this SP in form of strings
'0-30', '31-60', '61-90', and '91+'. The IN param is of course VARCHAR2.
What I want to do in this AND clause
e.g. for age range '0-30', the AND clause should be
AND age BETWEEN ( if this range is '0-30' then ) 0 AND 30 ( if range is '31-60') then BETWEEN 31 AND 60.. and so on...
However this BETWEEN will work till 61-90 range but for 91+ , there is no upper bound so it should be
AND age>91
Now , i am not sure how to achieve this both BETWEEN and '>' clauses in the same AND statement.
DECODE will not work and am not sure how to use the CASE in this situation as even that can not solve this issue.
Dont want to make the last AND clause dynamic
Please suggest me how to do this.
Thanks,
Aashish
Edited by: Aashish S. on Oct 21, 2011 6:01 PMA third alternative would be to choose a suitably large value as a high end for the 91+ group and use something like:
age between to_number(CASE WHEN instr(:param, '+') = 0
THEN substr(:param, 1, instr(:param, '-') -1)
ELSE substr(:param, 1, instr(:param, '+') -1) end) and
to_number(CASE WHEN instr(:param, '+') = 0
THEN substr(:param, instr(:param, '-') +1)
ELSE '9999' END)John
Maybe you are looking for
-
Problem with Access privleges on FAT32 volumes
I recently installed leopard and boot camped a windows xp professional sp2 on a separate fat 32 volume. I also have an external firewire drive that is fat 32 as well. When i used tiger, i had no problems accessing these files. Now, i can access them
-
Hi, I would like to develop a user interface in labview environment. i would like to develop pipe and instrumentation diagram(flow control with valves,pipe etc). so now my question is. does labview offers symbols for Pipe and instrumentation diagram?
-
I build one custom integrator when I upload the data it show the following error SQL exception occurred during PL/SQL Upload which package i used in this integrator work fine with same parameter from back end while in excel it show the above error ho
-
Hi all, I have 2 date fields in a page: Start Date, End Date. The Start Date should not be later than End Date. I don't know how to write a validation to control TWO fields. I cannot use the built-in ADF declarative validation at Entity Level, since
-
On our website, championbaptist.com, we want to use FLV files. They work great locally, but do not play when uploaded to our web host. The actual page that has the video inserted is www.championbaptist.com/multimedia_Dec06.htm. I have been told by ou