[Solved] why would a date comparison involving DATE_ADD in mysql fail, but comparing as strings work?

How to optimize this SQL query?

In case you have your own slow SQL query, you can optimize it automatically here.

For the query above, the following recommendations will be helpful as part of the 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 Calling Functions With Indexed Columns (query line: 9): When a function is used directly on an indexed column, the database's optimizer won’t be able to use the index. For example, if the column `StartTime` is indexed, the index won’t be used as it’s wrapped with the function `DATE_ADD`. If you can’t find an alternative condition that won’t use a function call, a possible solution is to store the required value in a new indexed column.
  2. Use UNION ALL instead of UNION (query line: 47): Always use UNION ALL unless you need to eliminate duplicate records. By using UNION ALL, you'll avoid the expensive distinct operation the database applies when using a UNION clause.
The optimized query:
SELECT
        StartTime AS ID,
        StartTime,
        (SELECT
            GROUP_CONCAT(B.intActivityID) 
        FROM
            tblBookings B 
        WHERE
            B.dtmDateTime = DATE_ADD(STR_TO_DATE(CONCAT('2015-08-21 ', StartTime), '%Y-%m-%d %H:%i'), INTERVAL 1 DAY)) AS `Sat` 
    FROM
        (SELECT
            '10:00' AS StartTime 
        UNION
        SELECT
            '10:30' 
        UNION
        SELECT
            '11:00' 
        UNION
        SELECT
            '11:30' 
        UNION
        SELECT
            '12:00' 
        UNION
        SELECT
            '12:30' 
        UNION
        SELECT
            '13:00' 
        UNION
        SELECT
            '13:30' 
        UNION
        SELECT
            '14:00' 
        UNION
        SELECT
            '14:30' 
        UNION
        SELECT
            '15:00' 
        UNION
        SELECT
            '15:30' 
        UNION
        SELECT
            '16:00'
    ) AS X

Related Articles



* original question posted on StackOverflow here.