MySQL: Select “last month” records

MySQL: Select “last month” records

In order to select last month records you have to get first day of the last month and the last day of the first month. With this you use the mysql function BETWEEN.

Remember that current month could be January and the last month will in another year.

Finding first day of the last month:

DATE_FORMAT(CURRENT_DATE – INTERVAL 1 MONTH, "%Y-%m-01")

Finding the last thay of the last month:

LAST_DAY(CURRENT_DATE – INTERVAL 1 MONTH)

And the final Query is:

SELECT *
FROM `my_table`
`DATE` BETWEEN DATE_FORMAT(CURRENT_DATE – INTERVAL 1 MONTH, "%Y-%m-01") AND LAST_DAY(CURRENT_DATE – INTERVAL 1 MONTH)

No comments.