Home >Database >Mysql Tutorial >How to Efficiently Retrieve Last Month's Records from a SQL Server Table?
Problem:
Obtain the records from the database table [member] that fall within the previous month, based on the date_created field.
Solution:
To efficiently and accurately retrieve last month's records, we need to avoid certain pitfalls and employ the following approach:
Use Exclusive Range Filtering:
Instead of using inclusive ranges (e.g., BETWEEN operator), use exclusive range filtering with the > and < operators. This ensures that records from both the first and last day of the month are included.
Calculate Month Boundaries:
Derive the start of the previous month and the start of the current month using appropriate date functions. This avoids potential issues caused by inclusive upper-bound ranges.
Sample 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
This approach ensures that indices are used, data corruption is prevented, and the correct records are retrieved within the specified timeframe.
The above is the detailed content of How to Efficiently Retrieve Last Month's Records from a SQL Server Table?. For more information, please follow other related articles on the PHP Chinese website!