Sql Server: Get data for only the past year
Fetch data from the last year using DATEADD
paired with GETDATE()
:
This snippet discards all rows with dates in your_date_column
older than a year from the present date.
Time Zone and Format Aware
We need to account for time zones and enforce date formatting if our SQL Server operates across diverse global regions or demands a specific date format:
In this code, the SWITCHOFFSET function manages time zone offsets and ensures we're comparing accurate current times, irrespective of server location.
Dynamic and Comprehensive Queries
To design more sophisticated and practical SQL queries, it is smarter to create dynamic range queries without any manual adjustments:
This statement ensures the exact previous year's data extraction, encompassing complete 365 days from the start of the day, not just the past 365 days.
Visualising the Process
Visualising the task like pruning a tree, the objective is retaining the fresh branches (data from the last year):
Key Point: The SQL query keeps the database populated only with the significant recent data from the past year, similar to pruning to maintain a tree's fresh growth.
Striking a Balance: Performance and Readability
While creating your SQL queries, striving for balance between performance and readability is crucial.
In this code, ensuring the date column you're filtering is indexed can dramatically boost your query's speed. Besides, including comments can quell future confusion!
Deciphering Date Filters
While working with dates, it's crucial to distinguish between data from the "past 365 days" and from the "previous calendar year" (Jan 1 to Dec 31 of last year):
This query specifically collects data from the previous calendar year, independent of the present date, and hence is potent for annual reports.
Was this article helpful?