SQL> select sysdate "Current date", sysdate - interval '5' day "INTERVAL" from dual; Current d INTERVAL --------- --------- 14-SEP-09 09-SEP-09
SQL> select sysdate "Current date", sysdate - interval '5' month "INTERVAL" from dual; Current d INTERVAL --------- --------- 14-SEP-09 14-APR-09
SQL> select sysdate "Current date", sysdate - interval '5' year "INTERVAL" from dual; Current d INTERVAL --------- --------- 14-SEP-09 14-SEP-04
How about if we try the following:
SQL> select to_date('31-AUG-2009','DD-MON-YYYY') - interval '6' month from dual; select to_date('31-AUG-2009','DD-MON-YYYY') - interval '6' month from dual * ERROR at line 1: ORA-01839: date not valid for month specified
The 31st of August minus 6 months would make it February 31st which doesn't exist. This is the ANSI standard!
SQL> select to_date('28-AUG-2009','DD-MON-YYYY') - interval '6' month from dual; TO_DATE(' --------- 28-FEB-09The correct way:
SQL> select add_months(to_date('31-AUG-2009'),-6) from dual; ADD_MONTH --------- 28-FEB-09Because ADD_MONTHS will round the date to the maximum date for that month.
Thanks for the write up! I was just wondering why don't we use interval more often since it has a more friendly syntax.
ReplyDelete