How can I pull data from my table for just the past two years?
Current attempt which isn't recognizing "DATEADD":
select *
from TABLE
where EVENTDATE >= DATEADD(year, -1, GETDATE())
PL/SQL suggests Oracle. The correct logic is:
where eventdate >= sysdate - interval '2' year
Oracle can be finicky about interval arithmetic in general, add_months()
is a good habit:
where eventdate >= add_months(sysdate, -24)
Of course, it depends what you mean by "2 year". If you mean since Jan 1st of the last calendar year:
where eventdate >= trunc(sysdate, 'YYYY') - interval '1' year
There is no problem when subtracting a year from January 1st.
- interval '730' day
if that is what you want. –
Nov 14, 2019 at 21:27
sysdate - interval '2' year
, it will fail with an exception on a leap day.
Nov 22, 2019 at 6:39
Assuming Oracle and 2 years as 730 days you can do as simple as:
select *
from table_name
where eventdate >= sysdate -730
;
When you add or subtract numbers from dates, oracle interpret the numbers as days.
Be aware that date
is actually a date-time type and sysdate
returns the current date-time. So if you are executing this query now at 10 pm it won't get the rows at 9 pm 2 years ago. Only the rows that are 10 pm or later.
You can remove (actually zero) the time of a date
type doing trunc(sysdate) -730
.
Also, the trunc
function has more options. See the documentation.
You can use the ADD_MONTHS function to compare to a valid date, 2 years in the past:
select *
from TABLE
where EVENTDATE >= ADD_MONTHS(sysdate, -24)
Note: sysdate - interval '2' year
will not yield a valid date on leap days (will raise exception ORA-01839), but ADD_MONTHS will give a valid date each time.
Following code is ugly but will do the job for you :)
select *
from TABLE
where EVENTDATE >= TO_DATE(to_char(SYSDATE, 'YYYY') - 1 || '-' || to_char(SYSDATE, 'MM-DD'),'YYYY-MM-DD')