Update:
See this blog post for an effective indexing strategy for your query using computed columns:
The basic idea is that we simply compute the rounded length and startDate for the ranges, and then look for them using equality conditions (which are good for B-Tree indices)
In MySQL and SQL Server 2008 you can use SPATIAL ( R-Tree ) indexes.
They are especially good for conditions such as "select all records with a given point within the range of records", which is your business.
You save start_date and end_date as the beginning and end of a LineString (converting them to UNIX timestamps of a different numeric value), index them with the SPATIAL index and find all such a LineString whose minimum bounding box ( MBR ) contains the date value in question using MBRContains .
See this blog post on how to do this in MySQL :
and performance overview for SQL Server :
The same solution can be applied to search for a given IP by the network ranges stored in the database.
This task, along with your request, is another frequently used example of such a condition.
Regular B-Tree indexes are not good if ranges can overlap.
If they can't (and you know it), you can use the brilliant solution suggested by @AlexKuznetsov
Also note that the performance of this request is completely dependent on your data distribution.
If you have many entries in B and several entries in A , you can simply build the index on B.dates and let TS/CIS go to A
This query will always read all rows from A and will use Index Seek in B.dates in a nested loop.
If your data is distributed in another way, i. e. you have many rows in A , but few in B , and the ranges are usually short, then you can slightly change the design of the tables:
A start_date interval_length
create a composite index on A (interval_length, start_date)
and use this query:
SELECT * FROM ( SELECT DISTINCT interval_length FROM a ) ai CROSS JOIN b JOIN a ON a.interval_length = ai.interval_length AND a.start_date BETWEEN b.date - ai.interval_length AND b.date