MySQL query for date range
Question
I need a SQL query for retrieving data which is included in selected time period, time period is string which user selects from calendar.
For example, if user selects time period '2012-07-01' to '2012-07-04' and I have the following table:
ID || start_date || end_date
1 || 2012-07-02 || 2012-07-04
2 || 2012-07-06 || 2012-08-05
3 || 2012-07-01 || 2012-09-01
4 || 2012-06-25 || 2012-09-01
If a write a sql query like this:
SELECT ID, start_date, end_date
FROM TABLE
WHERE start_date BETWEEN '2012-07-01' AND '2012-07-04'
This returns all rows which started from '2012-07-01' to '2012-07-04'
ID || start_date || end_date
1 || 2012-07-02 || 2012-07-04
3 || 2012-07-01 || 2012-09-01
But, I want all data which is included in this period, so result must be:
ID || start_date || end_date
1 || 2012-07-02 || 2012-07-04
3 || 2012-07-01 || 2012-09-01
4 || 2012-06-25 || 2012-09-01
Row with ID 4 also I want to be in result, because user selected time period is under start_date and end_date.
Solution
SELECT ID, start_date, end_date
FROM TABLE
WHERE start_date BETWEEN '2012-07-01' AND '2012-07-04'
You are only selecting by start date, you may ask by:
(start_date between begin, end) OR
(end_date between begin, end) OR
(start_date <= begin AND end_date >= end)
so:
(start_date between begin, end )
: you have all events that starts in the range
(end_date between begin, end)
: you have all events that finish in the range
(start_date <= begin AND end_date >= end)
: you have all events that are active in the range
OTHER TIPS
I think this is what you are looking for:
SELECT ID, start_date, end_date
FROM TABLE
WHERE start_date <= '2012-07-01' AND
end_date >= '2012-07-04';
You must to cover three types of events:
- Starting in this interval
- Ending in this interval
- Starting before and ending after the interval.
So you should use this:
SELECT ID, start_date, end_date
FROM your_table
WHERE (start_date BETWEEN '2012-07-01' AND '2012-07-04')
OR (end_date BETWEEN '2012-07-01' AND '2012-07-04')
OR (start_date <= '2012-07-01' AND
end_date >= '2012-07-04')
Quick overview:
Interval: S---------E
Case 1 : ---| : : NOT WANTED
Case 2 : ----------:----| : WANTED
Case 3 : ----------:---------:------ WANTED - YOUR PROBLEM
Case 4 : |------:----| : WANTED
Case 5 : |------:---------:------ WANTED
Case 6 : : |---| : WANTED
Case 7 : : |------:------ WANTED
Case 8 : : : |--- NOT WANTED
Your problematic case is the case 3. It will be covered by adding extra condition start_date <= '2012-07-01' AND end_date >= '2012-07-04'
.