Name

LAST_DAY()

Synopsis

LAST_DAY(date)

This function returns the date of the last day of the month for a given date or datetime value. NULL is returned for invalid dates. It’s available as of version 4.1.1 of MySQL. Here is an example:

SELECT LAST_DAY('2008-12-15')
AS 'End of Month';

+--------------+
| End of Month |
+--------------+
| 2008-12-31   |
+--------------+

There is no FIRST_DAY() function at this time. However, you can use LAST_DAY() in conjunction with a couple of other functions to return the first day of the month:

SELECT CURDATE( ) AS 'Today',
ADDDATE(LAST_DAY(SUBDATE(CURDATE(), INTERVAL 1 MONTH)), 1)
AS 'First Day of Month';

+------------+--------------------+
| Today      | First Day of Month |
+------------+--------------------+
| 2008-06-18 | 2008-06-01         | 
+------------+--------------------+

In this example, we are subtracting one month from the results of CURDATE() to get the same day last month. From there, we’re using LAST_DAY() to find the last day of last month. Then ADDDATE() is employed to add one day to the results, to find the first day of the month after last month, that is to say, the current month. This method adjusts for dates in January that would involve a previous year.

Get MySQL in a Nutshell, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.