How do you check for date range overlaps in SQL?
Checking for date range overlap is a deceptively simple problem that many engineers get wrong by trying to enumerate overlap cases. The correct approach is to use the complement: two ranges do NOT overlap when one ends before the other starts. Negating that gives the universal overlap condition.
For ranges [A.start, A.end) and [B.start, B.end), the overlap condition is:
`A.start < B.end AND A.end > B.start`
This single expression handles all overlap geometries: partial overlap from either side, one range fully contained within the other, and identical ranges. The boundary behavior depends on whether your ranges are inclusive or exclusive on the endpoints. For closed intervals [A.start, A.end], use `<=` instead of `<`.
In SQL, this is expressed as a WHERE clause predicate. To find all bookings that overlap with a candidate booking ('2024-01-10', '2024-01-15'):
```sql SELECT * FROM bookings WHERE start_date < '2024-01-15' AND end_date > '2024-01-10'; ```
For self-joins (finding all overlapping pairs within a table):
```sql SELECT a.id, b.id FROM bookings a JOIN bookings b ON a.id < b.id AND a.start_date < b.end_date AND a.end_date > b.start_date; ```
The `a.id < b.id` condition prevents returning both (A,B) and (B,A).
Some databases provide native range types. PostgreSQL has the `tsrange` / `daterange` types with the `&&` overlap operator, which is both more readable and index-optimizable via GiST indexes. For high-volume overlap queries (scheduling systems, calendar applications), a plain B-tree index on start_date and end_date is insufficient — a GiST index on a range column, or application-level interval tree structures, are needed for sub-linear performance.
States the correct overlap formula (A.start < B.end AND A.end > B.start), handles the boundary condition question, and writes a correct WHERE clause.
Derives the formula from the non-overlap complement rather than just reciting it, correctly handles inclusive vs exclusive intervals, writes a correct self-join query with the deduplication condition, and mentions indexing considerations (GiST for range types).
Reading the answer is step one. Explaining it unprompted — under interview pressure — is what actually matters. Get AI-graded feedback on your answer with follow-up probes on your weak points.
Get Graded — Free Assessment