[Solved] Select a record just if the one before it has a lower value takes too long and fail

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 OR Conditions By Using UNION (modified query below): In mosts cases, filtering using the OR operator cannot be applied using indexes. A more optimized alternative will be to split the query to two parts combined with a UNION clause, while each query holds one part of the original OR condition.
  2. Avoid Subqueries In From Clause (modified query below): The database cannot properly optimize subqueries in the FROM clause. Therefore, we recommend to extract the subqueries to temporary tables, index them and join to them in the outer query.
  3. 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.
  4. Prefer Inner Join Over Left Join (modified query below): We identified that one or more left joined entities (e.g. `b`) are used in the 'where' clause, in a way that allows to replace it with an optimized inner join. Inner joins can be fully optimized by the database, while Left joins apply limitations on the database's optimizer.
  5. Push Filtering Conditions Into Subqueries (modified query below): Parts of the WHERE clause can pushed from the outer query to a subquery / union clause. Applying those conditions as early as possible will allow the database to scan less data and run the query more efficiently.
  6. Use UNION ALL instead of UNION (query line: 48): 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.
Optimal indexes for this query:
ALTER TABLE `Customers` ADD INDEX `customers_idx_company_ip` (`Company`,`IP`);
ALTER TABLE `Printers` ADD INDEX `printers_idx_serialnumber` (`SerialNumber`);
ALTER TABLE `es_temp2` ADD INDEX `es_temp2_idx_remain_yellow` (`Remain_Toner_Yellow`);
ALTER TABLE `es_temp3` ADD INDEX `es_temp3_idx_serialnumber_remain_yellow` (`SerialNumber`,`Remain_Toner_Yellow`);
ALTER TABLE `es_temp5` ADD INDEX `es_temp5_idx_serialnumber` (`SerialNumber`);
The optimized query:
SELECT
        a_id,
        T,
        a_serialnumber,
        p_model,
        BeforeCountBlack,
        AfterCountBlack,
        BeforeCountCyan,
        AfterCountCyan,
        BeforeCountMagenta,
        AfterCountMagenta,
        BeforeCountYellow,
        AfterCountYellow 
    FROM
        ((SELECT
            a.ID AS a_id,
            DATE_FORMAT(a.Time,
            '%d/%m/%y') AS T,
            a.SerialNumber AS a_serialnumber,
            p.Model AS p_model,
            b.Remain_Toner_Black BeforeCountBlack,
            a.Remain_Toner_Black AfterCountBlack,
            b.Remain_Toner_Cyan BeforeCountCyan,
            a.Remain_Toner_Cyan AfterCountCyan,
            b.Remain_Toner_Magenta BeforeCountMagenta,
            a.Remain_Toner_Magenta AfterCountMagenta,
            b.Remain_Toner_Yellow BeforeCountYellow,
            a.Remain_Toner_Yellow AfterCountYellow 
        FROM
            es_temp2 a 
        INNER JOIN
            es_temp3 b 
                ON a.SerialNumber = b.SerialNumber 
                AND a.RowNumber = b.RowNumber + 1 
        INNER JOIN
            Printers p 
                ON a.SerialNumber = p.SerialNumber 
        INNER JOIN
            Customers c 
                ON p.IP = c.IP 
                AND c.Company = 5 
        WHERE
            (
                b.Remain_Toner_Yellow < a.Remain_Toner_Yellow 
                AND 1 = 1
            )) 
    UNION
    DISTINCT (SELECT
        a.ID AS a_id,
        DATE_FORMAT(a.Time,
        '%d/%m/%y') AS T,
        a.SerialNumber AS a_serialnumber,
        p.Model AS p_model,
        b.Remain_Toner_Black BeforeCountBlack,
        a.Remain_Toner_Black AfterCountBlack,
        b.Remain_Toner_Cyan BeforeCountCyan,
        a.Remain_Toner_Cyan AfterCountCyan,
        b.Remain_Toner_Magenta BeforeCountMagenta,
        a.Remain_Toner_Magenta AfterCountMagenta,
        b.Remain_Toner_Yellow BeforeCountYellow,
        a.Remain_Toner_Yellow AfterCountYellow 
    FROM
        es_temp4 a 
    LEFT JOIN
        es_temp5 b 
            ON a.SerialNumber = b.SerialNumber 
            AND a.RowNumber = b.RowNumber + 1 
    INNER JOIN
        Printers p 
            ON a.SerialNumber = p.SerialNumber 
    INNER JOIN
        Customers c 
            ON p.IP = c.IP 
            AND c.Company = 5 
    WHERE
        (b.Remain_Toner_Black < a.Remain_Toner_Black 
        AND b.Remain_Toner_Black >= 0) 
        OR (b.Remain_Toner_Cyan < a.Remain_Toner_Cyan 
        AND b.Remain_Toner_Cyan >= 0) 
        OR (b.Remain_Toner_Magenta < a.Remain_Toner_Magenta 
        AND b.Remain_Toner_Magenta >= 0))
) AS union1

Related Articles



* original question posted on StackOverflow here.