Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Oracle get all rows where mydate >= sysdate – 1 year

I have a DAY_DATE column that contains values such as ’11-2-2021′. I want to extract the rows where the value is within the last year or higher. Meaning that the current date is 11-3-2022, which means that I want to get all rows where the date is 11-3-2021 or sooner.

I tried the following:

SELECT * FROM TABLE_A
WHERE 1=1
AND TO_CHAR(DAG_DATUM_VERZONDEN, 'YYYYIW') >= TO_CHAR(SYSDATE, 'IYYYIW') - 52

However, this isn’t working as you cannot always substract 52 weeks. E.g. when you are in the 10th week of 2022, then you can only substract 2022 (it will not include anything from 2021, as it does not include a change in years). I again tried to do something else:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SELECT * FROM TABLE_A
WHERE 1=1
AND TO_CHAR(DAG_DATUM_VERZONDEN, 'YYYYMM') >= to_char(trunc(add_months(SYSDATE,-12),'YEAR'),'YYYYMM') 

However, this return everything from 2021, and not necessarly the rows that are higher than 11-3-2021. ANyone else that knows the answer to this problem? Thanks for any help in advance.

>Solution :

If DAG_DATUM_VERZONDEN column’s datatype is DATE (should be; I hope it isn’t VARCHAR2), then

SELECT *
  FROM table_a
 WHERE dag_datum_verzonden >= ADD_MONTHS (TRUNC (SYSDATE), -12)

If you do store dates as strings (once again, bad idea), then first convert it (the string) to a valid date value:

 WHERE TO_DATE(dag_datum_verzonden, 'dd-mm-yyyy') >= ADD_MONTHS (TRUNC (SYSDATE), -12)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading