views:

229

answers:

3

I'm trying to find an integer number of days between two dates in Oracle 11g.

I can get close by doing

select sysdate - to_date('2009-10-01', 'yyyy-mm-dd') from dual

but this returns an interval, and I haven't been successful casting this to an integer.

Edit: Apparently in 10g, this returns the number of days as an integer.

+1  A: 

I figured it out myself. I need

select extract(day from sysdate - to_date('2009-10-01', 'yyyy-mm-dd')) from dual
Brian Ramsay
Weird. As with the other answerers, when I do your original query, I get a number, not an interval. And when I try your solution, I get an error, ORA-30076: invalid extract field for extract source. This is in Oracle 10g; what version are you using?
Dave Costa
11g. That could be it. Thanks Dave.
Brian Ramsay
Using systimestamp instead of sysdate means that it does timestamp rather than date arithmetic, which gives INTERVALs as a result. But I can't reproduce your experience with sysdate.
Gary
A: 

you can do :

select trunc(sysdate - to_date('2009-10-01', 'yyyy-mm-dd')) as days from dual

Sabeen Malik
trunc() did not work for me. I got this error: inconsistent datatypes: expected NUMBER, got INTERVAL DAY TO SECOND
Brian Ramsay
oh yeah .. cause u dont have the HH24:MI:SS part in the second date .. glad u got it figured out urself
Sabeen Malik
+1  A: 

Or you could have done this:

select trunc(sysdate) - to_date('2009-10-01', 'yyyy-mm-dd') from dual

This returns a NUMBER of whole days:

SQL> create view v as 
  2  select trunc(sysdate) - to_date('2009-10-01', 'yyyy-mm-dd') diff 
  3  from dual;

View created.

SQL> select * from v;

      DIFF
----------
        29

SQL> desc v
 Name                   Null?    Type
 ---------------------- -------- ------------------------
 DIFF                            NUMBER(38)
Tony Andrews
This still returns an INTERVAL DAY TO SECOND
Brian Ramsay
No it doesn't, what makes you say that?
Tony Andrews
Proof that it returns a NUMBER and not an INTERVAL DAY TO SECOND added to answer.
Tony Andrews