Skip to main content
Documents
Share
LinkedIn
Facebook
Twitter
Copy
ClausesStatementsKeywordsExpressionsFunctions

MySQL LAST_DAY() Function

The `LAST_DAY()` function in MySQL returns the last day of the month for a given date. It is commonly used for date calculations and reporting tasks that require end-of-month data.

Usage

The `LAST_DAY()` function determines the final calendar day of the month for any date. It is especially useful in financial and inventory applications.

LAST_DAY(date)

In this syntax, `date` is the date from which you want to find the last day of the month.

Examples

1. Basic Usage

SELECT LAST_DAY('2023-10-15');

In this example, the function returns `2023-10-31`, the last day of October 2023.

2. Using with Current Date

SELECT LAST_DAY(CURDATE());

This example returns the last day of the current month based on the system's current date.

3. Combining with Other Functions

SELECT LAST_DAY(DATE_ADD('2023-01-15', INTERVAL 1 MONTH));

Here, the `LAST_DAY()` function is used with `DATE_ADD()` to determine the last day of the month following January 2023, returning `2023-02-28`.

4. Edge Case: Leap Year

SELECT LAST_DAY('2024-02-10');

For leap years, the function correctly returns `2024-02-29`, demonstrating its ability to handle February dates in leap years.

5. Handling Invalid Dates

SELECT LAST_DAY('2023-02-30');

If a non-existent date is passed, MySQL returns `NULL`, highlighting the importance of input validation.

Tips and Best Practices

  • Validate Input Dates and Timezones: Ensure the date passed to `LAST_DAY()` is in a valid format and consider timezone settings that might affect date calculations when using server-specific dates.
  • Use with Date Arithmetic: Combine with functions like `DATE_ADD()` and `DATE_SUB()` for complex date calculations involving month ends.
  • Index Optimization: While indexing date columns can improve performance when frequently using `LAST_DAY()` in queries, it should be done judiciously as it may also increase the overhead for write operations.