Home >Database >Mysql Tutorial >How to Efficiently Retrieve Records from the Last Month in SQL Server?
To retrieve records from the last month, we need to use the date_created field in the member table. Here's a query that will accomplish this task:
WHERE date_created >= @startOfPreviousMonth AND date_created < @startOfCurrentMonth
To ensure that indices are used and incorrect data is excluded, we need to calculate the @startOfPreviousMonth and @startOfCurrentMonth variables as follows:
DECLARE @startOfCurrentMonth DATETIME SET @startOfCurrentMonth = DATEADD(month, DATEDIFF(month, 0, CURRENT_TIMESTAMP), 0) DECLARE @startOfPreviousMonth DATETIME SET @startOfPreviousMonth = DATEADD(month, -1, @startOfCurrentMonth)
Finally, the modified query would look like this:
SELECT * FROM Member WHERE date_created >= @startOfPreviousMonth AND date_created < @startOfCurrentMonth
This approach ensures optimal performance and data accuracy.
The above is the detailed content of How to Efficiently Retrieve Records from the Last Month in SQL Server?. For more information, please follow other related articles on the PHP Chinese website!