Comparing the Oracle Interval Data Type

jeffspost picture jeffspost · Jul 2, 2010 · Viewed 7.6k times · Source

I have an oracle time interval in a select statement like this:

SELECT ...
    CASE WHEN date1 - date2 > 0 
    THEN 'No'
    ELSE 'YES'
END 

This fails with an invalid data type. So I tried this, and it still fails.

SELECT ...
    CASE WHEN date1 - date2 > (sysdate - sysdate) 
    THEN 'No'
    ELSE 'YES'
END 

Is there any way to compare interval types?

Answer

APC picture APC · Jul 2, 2010

Your question mentions the INTERVAL datatype, although it is not clear from your examples where or if that is happening. Arithmetic with dates and intervals is quite simple;

SQL> select d1
  2         , d2
  3         , case when d2  > d1 + to_dsinterval ('10 0:0:0')
  4                 then 'no'
  5                 else 'yes' end
  6  from t34
  7  /

D1        D2        CAS
--------- --------- ---
02-JUL-10 25-JUN-10 yes
02-JUL-10 24-AUG-10 no
02-JUL-10 26-MAY-10 yes
02-JUL-10 25-JUL-10 no
02-JUL-10 15-APR-09 yes
02-JUL-10 13-JUL-10 no

6 rows selected.

SQL>

When both columns are of INTERVAL datatype, arithmetic clearly works:

SQL> select intvl1
  2         , intvl2
  3         , case when intvl2  > intvl1
  4                 then 'no'
  5                 else 'yes' end
  6  from t34
  7  /

INTVL1               INTVL2               CAS
-------------------- -------------------- ---
+10 00:00:00.000000  +07 00:00:00.000000  yes
+10 00:00:00.000000  -53 00:00:00.000000  yes
+10 00:00:00.000000  +37 00:00:00.000000  no
+10 00:00:00.000000  -23 00:00:00.000000  yes
+10 00:00:00.000000  +78 00:00:00.000000  no
+10 00:00:00.000000  -11 00:00:00.000000  yes

6 rows selected.

SQL>

Comparing the difference between two dates and an interval is a cinch...

SQL> select d1
  2         , d2
  3         , intvl1
  4         , case when  numtodsinterval(d1-d2, 'DAY') > intvl1
  5                 then 'no'
  6                 else 'yes' end
  7  from t34
  8  /

D1        D2        INTVL1               CAS
--------- --------- -------------------- ---
02-JUL-10 25-JUN-10 +10 00:00:00.000000  yes
02-JUL-10 24-AUG-10 +10 00:00:00.000000  yes
02-JUL-10 26-MAY-10 +10 00:00:00.000000  no
02-JUL-10 25-JUL-10 +10 00:00:00.000000  yes
02-JUL-10 15-APR-10 +10 00:00:00.000000  no
02-JUL-10 13-JUL-10 +10 00:00:00.000000  yes

6 rows selected.

SQL>

In short, it is difficult to understand what you are doing to get an error. So you need to edit your question and provide more details. Describe the table. Provide some sample data. Also, give us the entire error message.