[Solved] Optimizing A Slow Complicated Remote SQL Query

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 Correlated Subqueries (query line: 17): A correlated subquery is a subquery that contains a reference (column: ItemNumber) 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.
  2. Avoid Correlated Subqueries (query line: 28): A correlated subquery is a subquery that contains a reference (column: ItemNumber) 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: 49): A correlated subquery is a subquery that contains a reference (column: ItemNumber) 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. Avoid Correlated Subqueries (query line: 58): A correlated subquery is a subquery that contains a reference (column: ItemNumber) 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.
  5. 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.
  6. 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.
  7. Prefer Inner Join Over Left Join (modified query below): We identified that one or more left joined entities (e.g. `ITEM2`) 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.
  8. Use UNION ALL instead of UNION (query line: 39): 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 `ITEM1` ADD INDEX `item1_idx_item_id_month_ending` (`item_id`,`month_ending`);
ALTER TABLE `ITEM2` ADD INDEX `item2_idx_item_id_month_ending` (`item_id`,`month_ending`);
The optimized query:
SELECT
        DateElement,
        a_sourcestore,
        Cost 
    FROM
        ((SELECT
            GETDATE() AS DateElement,
            A.SourceStore AS a_sourcestore,
            COALESCE(FR.original_cost,
            CO.original_cost) AS Cost 
        FROM
            #TEMPA A 
        INNER JOIN
            REMOTEDB.ITEM1 CO 
                ON CO.item_id = A.ItemNumber 
                AND CO.month_ending >= (
                    SELECT
                        MAX(CO2.month_ending) 
                FROM
                    REMOTEDB.ITEM1 CO2 
                WHERE
                    CO2.item_id = A.ItemNumber
            ) 
        INNER JOIN
            REMOTEDB.ITEM2 FR 
                ON FR.item_id = A.ItemNumber 
                AND FR.month_ending >= (
                    SELECT
                        MAX(FR2.month_ending) 
                FROM
                    REMOTEDB.ITEM2 FR2 
                WHERE
                    FR2.item_id = A.ItemNumber
            ) 
        WHERE
            FR.item_id IS NOT NULL
        ) 
    UNION
    DISTINCT (SELECT
        GETDATE() AS DateElement,
        A.SourceStore AS a_sourcestore,
        COALESCE(FR.original_cost,
        CO.original_cost) AS Cost 
    FROM
        #TEMPA A 
    INNER JOIN
        REMOTEDB.ITEM1 CO 
            ON CO.item_id = A.ItemNumber 
            AND CO.month_ending >= (SELECT
                MAX(CO2.month_ending) 
        FROM
            REMOTEDB.ITEM1 CO2 
        WHERE
            CO2.item_id = A.ItemNumber) 
    LEFT JOIN
        REMOTEDB.ITEM2 FR 
            ON FR.item_id = A.ItemNumber 
            AND FR.month_ending >= (SELECT
                MAX(FR2.month_ending) 
        FROM
            REMOTEDB.ITEM2 FR2 
        WHERE
            FR2.item_id = A.ItemNumber) 
    WHERE
        CO.item_id IS NOT NULL)
    ) AS union1

Related Articles



* original question posted on StackOverflow here.