I'm working with an existing table that stores a start date, end date, and an integer used for ordering.
For a given start & end date, I need to be able to determine the smallest available integer for entries with an overlapping date range.
So for example, my table might store these records:
July 8th -> July 9th with an ordering index of 0.
July 9th -> July 10th with an ordering index of 1.
July 9th -> July 11th with an ordering index of 2.
Then, given the date range July 10th -> July 11th, I would want to set the ordering index to 0.
It needs to work where there could be no other entries within the entry date range (so it could default to 0). Date ranges aren't always two dates apart, and the ordering index doesn't have a limit.
Here is what I have that only returns one above the maximum order index:
SELECT ISNULL(MAX(order_index),-1) + 1 FROM table
WHERE start_date <= @end AND end_date >= @start)
I tried working with this answer, but couldn't get the desired result.