sqlplsql

SQL pull data for the past two years


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())

Solution

  • 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.