My MySQL database table has dates stored in the MySQL format (YYYY-MM-DD). I need to construct an SQL query that will return rows with dates that either occur today or yesterday or a day before. For example, if the stored date is 1979-08-22, I would like this row returned if today is 8/22 (the same date in a different year) or 8/23 or 8/24.
I’m thinking of using the DAYOFYEAR() function, which returns a single value between 1 and 365 depending on the date. Here is the current query:
SELECT * FROM `theTable` WHERE DAYOFYEAR(CURDATE())-DAYOFYEAR(`theDate`) IN(0, 1, 2, -364, -363)
This query finds the difference in days between the current date and the stored date and if it’s 3 days, it should return the result. It seems to work.
Is this the right way to achieve the result I want or is there another, more efficient way? Is this likely to cause issues with leap years?
Done!