to find rows that do not overlap (assuming that start_date_time is always before end_date_time, and both are non-null) we could use a test like this:
WHERE r.end_date_time < '2019-03-21 00:00'
OR r.start_date_time >= '2019-03-22 00:00'
If the “end” on the row is before the start of the range we want to test, there is no overlap. Or, if the “start” on the row is on or after the end of the range, there is no overlap.
This is checking for any overlap at any time on 3/21/2019. (“start” is 3/21, and “end” is 3/22.)
Inverting that condition would give us rows that do overlap:
WHERE NOT ( r.end_date_time < '2019-03-21 00:00'
OR r.start_date_time >= '2019-03-22 00:00'
)
Which can be rewritten:
WHERE r.end_date_time >= '2019-03-21 00:00'
AND r.start_date_time < '2019-03-22 00:00'
(Note that we need a more elaborate condition, if the values of start_date_time and/or end_date_time can be NULL, or if end_date_time can be before start_date_time.)
Since you only have a DATE (no time) and you need to check with a DATETIME, then ignore the time. Extract the DATE portion of the DATETIME column and check if your date is between those dates:
SELECT * FROM table_name
WHERE '2019-03-21' BETWEEN DATE(StartDateTime) AND DATE(EndDateTime)
Doing the opposite may also work:
SELECT * FROM table_name
WHERE CAST('2019-03-21' AS DATETIME) BETWEEN StartDateTime AND EndDateTime
4
Answers
You can use the date function:
Source: date
You want:
However, the most efficient way to write the query would be:
We’d need to check for an overlap, of datetime values from the rows, with start and end datetime
visually, given a start and end we want to check overlap for, there are several possibilities:
to find rows that do not overlap (assuming that start_date_time is always before end_date_time, and both are non-null) we could use a test like this:
If the “end” on the row is before the start of the range we want to test, there is no overlap. Or, if the “start” on the row is on or after the end of the range, there is no overlap.
This is checking for any overlap at any time on 3/21/2019. (“start” is 3/21, and “end” is 3/22.)
Inverting that condition would give us rows that do overlap:
Which can be rewritten:
(Note that we need a more elaborate condition, if the values of start_date_time and/or end_date_time can be NULL, or if end_date_time can be before start_date_time.)
Since you only have a
DATE
(no time) and you need to check with aDATETIME
, then ignore the time. Extract theDATE
portion of theDATETIME
column and check if your date is between those dates:Doing the opposite may also work: