Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best SQL query to select events between two dates

After read a lot of posts about this. I need a good way to select events between two dates. The possible conditions are shown in the following figure:

Date range for events

My first attempt is the following:

SELECT *
FROM events
WHERE 
(
 start_date BETWEEN $start_select AND  $end_select
 OR
 end_date BETWEEN $start_select AND $end_select
)
OR
(
 start_date <=  $start_select
 AND
 end_date >= $end_select
)

The problem is that it takes a long time to make the query.

Then I saw this post: Select data from date range between two dates where @dmlukichev talks about exclude all wrong options:

Something like this:

SELECT *
FROM events
WHERE NOT 
(
 start_date <  $start_select
 OR
 end_date > $end_select
)

But it does not work me.

Any ideas?

like image 999
kurtko Avatar asked Dec 18 '22 23:12

kurtko


1 Answers

If I am getting the condition right, this is what you need.

SELECT * FROM events WHERE (end_date >=  $start_select AND start_date <= $end_select);

You will get all events where the start date is before the $end_select and the end date is after $start_select.

like image 132
Yasen Zhelev Avatar answered Jan 10 '23 02:01

Yasen Zhelev