[Solved] Date range between two date columns

EverSQL Database Performance Knowledge Base

Date range between two date columns

Database type:

I have these two columns:

start_dt                  end_dt
2013-09-18 14:00:00       2013-09-18 16:00:00 

I want to select the rows between these two dates (stored as datetime in MYSQL), so...

FROM task_schedule_times
WHERE `start_dt` >= "2013-09-18 14:00:00"
AND `end_dt` <= "2013-09-18 16:00:00"

This is fine, but I need to be able to return the above row if searching for any dates within start_dt and end_dt:

"2013-09-18 15:00:00" and "2013-09-18 15:30:00"

Visual representantion (the line represents a time interval):

entry1: -----------------
select:     ---------

I also need to return the row if the date range supplied falls anywhere within range of the row

entry1: -----------------
select:     ----------------------


entry1:          -----------------
select: -----------------

No results should be displayed in a case like so:

entry1:        -----------------
select: -------

Hopefully these creative inputs explain things better than I can with words.

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Avoid Selecting Unnecessary Columns (query line: 2): Avoid selecting all columns with the '*' wildcard, unless you intend to use them all. Selecting redundant columns may result in unnecessary performance degradation.
  2. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
Optimal indexes for this query:
ALTER TABLE `task_schedule_times` ADD INDEX `task_times_idx_start_dt` (`start_dt`);
The optimized query:
        task_schedule_times.`start_dt` >= '2013-09-18 14:00:00' 
        AND task_schedule_times.`end_dt` <= task_schedule_times."2013-09-18 16:00:00"

Related Articles

* original question posted on StackOverflow here.