5

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?

Community
  • 1
  • 1
kurtko
  • 1,978
  • 4
  • 30
  • 47

2 Answers2

11

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.

Yasen Zhelev
  • 4,045
  • 3
  • 31
  • 56
  • The problem is the next: if you select the last day (or first) it does not work. For example I have an event from '25-10-2015' to '29-10-2015' then my select range is '29-10-2015' to '31-10-2015', your query doesn't work. – kurtko Oct 19 '15 at 09:15
  • 1
    I think: SELECT * FROM events WHERE (end_date >= $start_select AND start_date <= $end_select); – kurtko Oct 19 '15 at 09:19
  • Yes, you are right. I was not sure should I include the actual dates in the check. I updated my answer. – Yasen Zhelev Oct 19 '15 at 09:20
0

Might be a bit late (by 4 years) but I use:

SELECT * FROM events WHERE  (end_date > $start_select AND start_date BETWEEN $start_select AND $end_select
    OR start_date < $end_select AND end_date BETWEEN $start_select AND $end_select
    OR (start_date < $start_select AND end_date > $end_select) BETWEEN $start_select AND $end_select
    )
CharlesdeK
  • 13
  • 5
  • Logically, this is correct, your expressions cover all 3 uses cases. 1) The event's start date is within the selected range (or) 2) The event's end date is within the selected range (or) 3) The event fully encompasses the selected date range. I'm only commenting because your logic works and embraces real scenarios which is easily explainable to other developers. However, this is not the most concise solution (Answered above). – Aries Apr 08 '22 at 06:42