Home > other >  How to select 2-year time range based on a date - MySQL?
How to select 2-year time range based on a date - MySQL?

Time:10-01

I know how to select several days based on a date:

WHERE 
    date_column > adddate('2021-09-29', -100)
AND 
    date_column < '2021-09-29'

The query above select the data where date_column is between 100days before 2021-09-29 and 2021-09-29.

My question is can I use the same pattern/syntax for year and how to do it? Is it something like adddate('2021-09-29', -2y)?

I know I can do something like date_column BETWEEN '2021-09-29' - INTERVAL 2 YEAR AND '2021-09-29', but I don't want to use this syntax, can I use something similar to the syntax in the top example because I'll need it in my Python code? Thanks.

CodePudding user response:

You could use DATE_ADD('2021-09-29', INTERVAL -2 YEAR). See this.

You could do something like this:

MAKEDATE(YEAR('2021-09-29')   2, DAYOFYEAR('2021-09-29'))

Any date arithmetic you do "yourself" needs to be tested carefully for leap-year edge cases. Not worrying about those edge cases is the biggest and best reason to use the built-in date arithmetic operations. Lest your project be featured on https://worsethanfailure.com/ , which you do not want to happen.

(They do have strange syntax, eh?)

  • Related