Home > Database > Mysql Tutorial > How to Get the Last Day of Any Month in SQL?

How to Get the Last Day of Any Month in SQL?

Patricia Arquette
Release: 2025-01-08 11:16:41
Original
1009 people have browsed it

How to Get the Last Day of Any Month in SQL?

Get the last day of the month in SQL

In database management, it is often necessary to operate on dates and extract specific information from them. A common task is to determine the last day of a given month. This guide explores how to achieve this in SQL for any arbitrary date.

If you know the first day of the month, add a month and subtract a day to get the last day, as shown in the query below:

<code class="language-sql">DATEADD(DAY, DATEADD(MONTH, '2009-05-01', 1), -1)</code>
Copy after login

However, to generalize this process to any given date, a more robust solution is required.

Using the EOMONTH function (SQL Server 2012 and later)

SQL Server 2012 and later introduces the EOMONTH function, which provides a convenient way to determine the last day of the month. The syntax is as follows:

<code class="language-sql">EOMONTH(start_date, [month_to_add])</code>
Copy after login

Among them:

  • start_date is the date from which you want to calculate the last day of the month.
  • month_to_add (optional) Specifies the month offset to add to start_date before finding the last day of the month.

Usage Example

To find the last day of the month for a given date, just use the EOMONTH function as follows:

<code class="language-sql">SELECT EOMONTH(@SomeGivenDate)</code>
Copy after login

This query will return the last day of the month containing the specified @SomeGivenDate.

The above is the detailed content of How to Get the Last Day of Any Month in SQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template