I have two tables that store similar data but for different time periods:
MainTable: contains records for the current year.
ArchiveTable: contains records from previous years.
Both tables have a column named DateColumn (of type DATETIME). I need to write a T‑SQL query (or set of queries) that behaves as follows based on two input parameters, @StartDate and @EndDate:
Current Year Only: If both dates fall within the current year, fetch data only from MainTable.
Previous Years Only: If both dates are before the current year, fetch data only from ArchiveTable.
Mixed Range: If the date range spans previous years and the current year, fetch data from both tables.
For example, if the current year is 2025:
@StartDate = '2025-03-01' and @EndDate = '2025-03-31' should return rows from MainTable only.
@StartDate = '2024-11-01' and @EndDate = '2024-12-31' should return rows from ArchiveTable only.
@StartDate = '2024-12-15' and @EndDate = '2025-01-15' should return rows from both tables (split at the boundary).
I have considered using IF…ELSE logic to decide which table to query, but I’m looking for advice on the best or most elegant way to implement this (perhaps in a single query, using UNION ALL or dynamic SQL).
What are the best practices or alternative methods for implementing this logic? Can this be achieved in a single query or via other techniques that might simplify maintenance?
UNION ALLquery with separateWHEREfilters?