Home >Database >Mysql Tutorial >How to Retrieve Records from the Previous Month in SQL Server?

How to Retrieve Records from the Previous Month in SQL Server?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-04 10:17:40211browse

How to Retrieve Records from the Previous Month in SQL Server?

Retrieving Records from the Previous Month in SQL Server

To retrieve records from the last month based on the date_created field in the member table, you can use SQL to execute the following query:

DECLARE @startOfCurrentMonth DATETIME
SET @startOfCurrentMonth = DATEADD(month, DATEDIFF(month, 0, CURRENT_TIMESTAMP), 0)

SELECT *
FROM Member
WHERE date_created >= DATEADD(month, -1, @startOfCurrentMonth)
      AND date_created < @startOfCurrentMonth

Explanation:

  • @startOfCurrentMonth is a variable that stores the start of the current month.
  • DATEADD(month, -1, @startOfCurrentMonth) calculates the start of the previous month.
  • The WHERE clause filters the records based on the following conditions:

    • date_created is greater than or equal to the start of the previous month.
    • date_created is less than the start of the current month.

This query ensures that indices on the date_created column can be utilized for faster execution and that no unintended dates or data are included in the results.

The above is the detailed content of How to Retrieve Records from the Previous Month in SQL Server?. 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