How to Get the Last Day of the Month in SQL

To find the last day of the month in SQL, use the LAST_DAY() function. This function takes a single argument, which is the date you want to find the last day of the month for. For example, if you wanted to find the last day of the month for the date 2020-06-15, you would use the following query:

SELECT LAST_DAY('2020-06-15');

This query would return the result 2020-06-30, since June 30th is the last day of the month for the given date.

Examples

Let's look at a few examples of how this function can be used. Suppose you have a table called orders with the following data:

orders
order_date
2020-06-15
2020-06-02
2020-07-20
2020-08-01


If you wanted to find the last day of the month for each of these dates, you would use the following query:

SELECT LAST_DAY(order_date) FROM orders;

This query would return the results 2020-06-30, 2020-07-31, 2020-07-31, and 2020-08-31, since those are the last days of the month for each of the given dates.

Additional Info

The LAST_DAY() function is supported by most major databases, including MySQL, PostgreSQL, and SQL Server. However, the syntax may vary slightly depending on the database you are using. For more information, check out the documentation for your particular database.

Want to build your own LLM Apps with AirOps👇👇