Sometimes there is a shorter solution

Sometimes, while we're developing, we find solutions to problems that work correctly. And sometimes, we think it is the best solution and stop thinking of other possibilities.

I had a recent example few days ago, while I was coding a SQL Server stored procedure that filtered date ranges, returning elements that fit in the first four of this six available outcomes:

Date range diagram: range B1-B2 lies entirely inside range A1-A2 (wanted match) #1 - Wanted

Date range diagram: B1 starts before A1 and B2 ends inside A1-A2, partial overlap (wanted match) #2 - Wanted

Date range diagram: B1 starts inside A1-A2 and B2 ends after A2, partial overlap (wanted match) #3 - Wanted

Date range diagram: range B1-B2 fully contains A1-A2 (wanted match) #4 - Wanted

Date range diagram: B1-B2 lies entirely after A2, no overlap (unwanted) #5 - Unwanted

Date range diagram: B1-B2 lies entirely before A1, no overlap (unwanted) #6 - Unwanted

In order to acomplish the four first situations, this would be the SQL comparisons needed:

B1>=A1 AND B2<=A2
+
B1<=A1 AND B2<=A2
+
B1>=A1 AND B2>=A2
+
B1<=A1 AND B2>=A2

But, there's sometimes a shorter solution... Like this one:

A1\<=B2 AND A2>=B1

Beautiful, don't you agree? Just by switching Bs we reduce to just one AND, covering all four desired causistics...

Sometimes we see a narrow passage (play with the lesser/greater operators) when there is more than one solution (playing with the Ax/Bx operands).

Tags: Databases Development Patterns & Practices SQL

The Sometimes there is a shorter solution article was written by Diego, originally published on