SQL Server – Check if Two Datetimes are Between Two Others

datetimesql server

Today I'm facing with problem, which I can't solve.

I need to check if two datetimes (2019-04-08 13:30:002019-04-08 15:30:00 ) are between or overlap two others (2019-04-08 14:00:002019-04-08 16:00).

Imagine that those datetimes are event's date. We can see that there is an event between 14:00 and 16:00 so we cant' have other between.

I've tried something like this:

SELECT * FROM Rezerwacja WHERE
(('2019-04-08 13:30:00.000' between Start and Stop) OR
('2019-04-08 15:30:00.000' between Start and Stop))

How to check if there is an "event" already ?

Best Answer

To check for overlaps, you only need 2 conditions, the start or interval A with the end of interval B, and vice versa:

WHERE
      '2019-04-08 13:30:00.000' < Stop 
  AND Start < '2019-04-08 15:30:00.000'