Home >Database >Mysql Tutorial >How to Efficiently Select the First Day of a Month in SQL?

How to Efficiently Select the First Day of a Month in SQL?

DDD
DDDOriginal
2025-01-17 23:01:09444browse

How to Efficiently Select the First Day of a Month in SQL?

Efficiently select the first day of the month in SQL

Retrieving the first day of the month from a given DateTime variable is a common task in database operations. While code using the CAST function is a possible solution, it's not the most efficient or elegant approach.

Better solution

To select the first day of the month, a more efficient way is to use the DATEADD and DATEDIFF functions. The following code demonstrates this technique:

<code class="language-sql">SELECT DATEADD(month, DATEDIFF(month, 0, @mydate), 0) AS StartOfMonth</code>

Instructions:

  • DATEDIFF(month, 0, @mydate) Calculates the difference between the given DateTime variable @mydate and the start of the current month (i.e. January 1st).
  • DATEADD(month, DATEDIFF(month, 0, @mydate), 0) Add the calculated difference back to the beginning of the current month to get the @mydate first day of the month.

This method is faster and more concise than the previous method using the CAST function.

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

Statement:
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