[Solved] MySQL, optimize query 10 sec execution

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 Using Date Functions In Conditions (query line: 19): When a function is used directly on an indexed column, the database's optimizer won’t be able to use the index. An alternative way is to use a range condition instead of a function call.
  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.
  3. Index Function Calls Using Generated Columns (modified query below): When a function is used directly on an indexed column, the database's optimizer won’t be able to use the index to optimize the search. Creating and indexing a generated column (supported in MySQL 5.7) will allow MySQL to optimize the search.
  4. Replace Left Join With Subquery (modified query below): The pattern of inflating the amount of data (using joins) and deflating (using GROUP BY) usually slows down queries. In this case, it can be avoided by moving some of the logic to the SELECT clause, and therefore removing some of the LEFT JOINs. In some cases, this transformation can lead to an obsolete GROUP BY clause, which can also be removed.
  5. Use Numeric Column Types For Numeric Values (query line: 32): Referencing a numeric value (e.g. 1) as a string in a WHERE clause might result in poor performance. Possible impacts of storing numbers as varchars: more space will be used, you won't be able to perform arithmetic operations, the data won't be self-validated, aggregation functions like SUM won't work, the output may sort incorrectly and more. If the column is numeric, remove the quotes from the constant value, to make sure a numeric comparison is done.
Optimal indexes for this query:
ALTER TABLE `Hours` ADD INDEX `hours_idx_subordinate_id_date_date` (`subordinate_id`,`date_date`);
ALTER TABLE `users` ADD INDEX `users_idx_discharge_role_active` (`discharge`,`role`,`active`);
The optimized query:
SELECT
        `User`.`id` AS id,
        `User`.`f_name` AS name,
        `User`.`l_name` AS surname,
        `User`.`discharge` AS discharge,
        (SELECT
            SUM(`Hour`.`normal`) + SUM(`Hour`.`full`) + SUM(`Hour`.`half`) workedHours 
        FROM
            `kadry`.`Hours` AS `Hour` 
        WHERE
            (
                `Hour`.`subordinate_id` = `User`.`id` 
                AND `Hour`.date_date BETWEEN '2016-06-01' AND '2016-06-30'
            ) LIMIT 1) workedHours,
        (SELECT
            (SUM(Hour.day_off_id = 16)) * 8 AS hourFracht 
        FROM
            `kadry`.`Hours` AS `Hour` 
        WHERE
            (
                `Hour`.`subordinate_id` = `User`.`id` 
                AND `Hour`.date_date BETWEEN '2016-06-01' AND '2016-06-30'
            ) LIMIT 1) AS hourFracht 
    FROM
        `kadry`.`users` AS `User` 
    WHERE
        (
            `User`.`discharge` IS NULL 
            OR `User`.`discharge` > '2016-06-30 23:59:59'
        ) 
        AND `User`.`role` = 'regular' 
        AND `User`.`active` = '1' 
    ORDER BY
        `User`.`assigned` ASC,
        `User`.`l_name` ASC

Related Articles



* original question posted on StackOverflow here.