[Solved] Is there a faster way of adding up time ranges, taking overlaps into account?

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: 32): 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 `overnight` is indexed, the index won’t be used as it’s wrapped with the function `COALESCE`. 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. Avoid Correlated Subqueries (query line: 6): A correlated subquery is a subquery that contains a reference (column: DateR1) to a table that also appears in the outer query. Usually correlated queries can be rewritten with a join clause, which is the best practice. The database optimizer handles joins much better than correlated subqueries. Therefore, rephrasing the query with a join will allow the optimizer to use the most efficient execution plan for the query.
  3. Avoid Correlated Subqueries (query line: 16): A correlated subquery is a subquery that contains a reference (column: TRANS_END) to a table that also appears in the outer query. Usually correlated queries can be rewritten with a join clause, which is the best practice. The database optimizer handles joins much better than correlated subqueries. Therefore, rephrasing the query with a join will allow the optimizer to use the most efficient execution plan for the query.
  4. 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.
  5. Explicitly ORDER BY After GROUP BY (modified query below): By default, the database sorts all 'GROUP BY col1, col2, ...' queries as if you specified 'ORDER BY col1, col2, ...' in the query as well. If a query includes a GROUP BY clause but you want to avoid the overhead of sorting the result, you can suppress sorting by specifying 'ORDER BY NULL'.
Optimal indexes for this query:
ALTER TABLE `Service` ADD INDEX `service_idx_sysid` (`SYSID`);
ALTER TABLE `Trans` ADD INDEX `trans_idx_chargeby_sysid` (`CHARGEBY`,`SYSID`);
ALTER TABLE `trans_workers` ADD INDEX `trans_workers_idx_trans_sysid` (`trans_sysid`);
The optimized query:
SELECT
        A.scheduled_hours = COALESCE(sum(A.hours),
        0),
        A.worker_sysid 
    FROM
        (SELECT
            DISTINCT B.DateR1,
            B.DateR2,
            hours = ABS((B.DateR1 - B.DateR2) / 3600),
            worker_sysid 
        FROM
            Trans A 
        JOIN
            trans_workers 
                ON A.SYSID = trans_workers.trans_sysid 
        OUTER APPLY (SELECT
            DateR1 = MIN(TRANS_START),
            DateR2 = MAX(TRANS_END),
            Trans.SYSID FROM
                Trans 
            LEFT JOIN
                Service 
                    ON Service.SYSID = Trans.SERVICESYSID 
            WHERE
                TRANS_START <= A.TRANS_END 
                AND TRANS_END >= A.TRANS_START 
                AND TRANS_START IS NOT NULL 
                AND TRANS_END IS NOT NULL 
                AND TRANS_START != '' 
                AND TRANS_END != '' 
                AND Trans.CHARGEBY IN ('Hours', 'Hour') 
                AND COALESCE(Service.overnight, 0) != 1 
                AND TRANSDATE BETWEEN 80387 AND 80400 
            GROUP BY
                Trans.SYSID 
            ORDER BY
                NULL) B
        ) A 
    WHERE
        A.worker_sysid IS NOT NULL 
    GROUP BY
        A.worker_sysid 
    ORDER BY
        A.worker_sysid

Related Articles



* original question posted on StackOverflow here.