Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding overlapping intervals using SQL

Tags:

sql

I want to extract rows from a table whose interval intersects with an interval specified in the query. Assuming that I have a simple ID, DATE_START, DATE_END table and two query parameters P_DATE_START and P_DATE_END, what is the simplest way of expressing the query so that I find all rows for which [DATE_START, DATE_END] has at least one common element with [P_DATE_START, P_DATE_END]?


Update:

To make the desired outcome clearer, please find a list of input values and expected outcomes below. Colums are DATE_START, DATE_END, P_DATE_START, P_DATE_END, MATCH.

16, 17, 15, 18, YES
15, 18, 16, 17, YES
15, 17, 16, 18, YES
16, 18, 15, 17, YES
16, 17, 18, 19, NO
18, 19, 16, 17, NO
like image 897
Robert Munteanu Avatar asked Oct 22 '25 16:10

Robert Munteanu


1 Answers

Even simpler:

SELECT id, date_start, date_end 
FROM thetable 
WHERE date_start <= p_date_end 
AND date_end >= p_date_start
like image 91
Ilya Kogan Avatar answered Oct 25 '25 06:10

Ilya Kogan