Search code examples
oracledate-arithmeticsql-date-functions

Date function on oracle


I've got a question about date function on oracle.

I have the following table

statistic_table(
   pages AS varchar(10),
   date_created AS date
);

I have the following sql

SELECT COUNT(*) FROM statistic_table WHERE date_created BETWEEN sysdate-5 AND sysdate-1
and
SELECT COUNT(*) FROM statistic_table WHERE date_created BETWEEN to_date('12-AUG-2011') AND to_date('16-AUG-2011');

the question is, why is it return different numbers. assuming sysdate-5 returns 12-aug-2011 and sysdate-1 returns 16-aug-2011

Any help would be much appreciated!

Cheers,


Solution

  • A date in Oracle is a point in time with a precision of a second.

    SYSDATE returns the current date and time and is therefore not the same as to_date('17-AUG-2011'):

    SQL> SELECT to_char(sysdate, 'dd-mon-yyyy hh24:mi:ss') FROM DUAL;
    
    TO_CHAR(SYSDATE,'DD-MON-YYYYHH
    ------------------------------
    17-aug-2011 15:52:13
    

    Use the TRUNC function if you only want the date component:

    SQL> SELECT to_char(trunc(sysdate), 'dd-mon-yyyy hh24:mi:ss') FROM DUAL;
    
    TO_CHAR(TRUNC(SYSDATE),'DD-MON
    ------------------------------
    17-aou-2011 00:00:00