[Solved] Is there a better query to achieve the same results

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. 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.
  2. 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'.
  3. Use UNION ALL instead of UNION (query line: 16): 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 `Ac2018` ADD INDEX `ac2018_idx_accesstype_utcaccesseddt` (`AccessType`,`UTCAccessedDT`);
ALTER TABLE `Ac2019` ADD INDEX `ac2019_idx_accesstype_utcaccesseddt` (`AccessType`,`UTCAccessedDT`);
ALTER TABLE `Ac2019` ADD INDEX `ac2019_idx_lbid` (`lbid`);
ALTER TABLE `Ass` ADD INDEX `ass_idx_associd` (`AssocID`);
ALTER TABLE `LBNames` ADD INDEX `lbnames_idx_topassembly` (`TopAssembly`);
ALTER TABLE `LockBox` ADD INDEX `lockbox_idx_lbid` (`LBID`);
The optimized query:
SELECT
        ass.Name,
        lbnm.ProductName,
        COUNT(*) AS lb_count 
    FROM
        (SELECT
            ac.lbid 
        FROM
            lockbox.Ac2018 ac 
        WHERE
            ac.AccessType NOT IN (
                'Gen'
            ) 
            AND ac.UTCAccessedDT > '2018-10-10 00:00:00' 
        UNION
        SELECT
            ac.lbid 
        FROM
            lockbox.Ac2019 ac 
        WHERE
            ac.AccessType NOT IN (
                'Gen'
            ) 
            AND ac.UTCAccessedDT > '2019-10-01 00:00:00' 
        GROUP BY
            ac.lbid
    ) p 
JOIN
    lockbox.LBMFG mfg 
        ON p.LBID = mfg.LBID 
JOIN
    lockbox.LockBox lb 
        ON mfg.LBID = lb.LBID 
JOIN
    lockbox.Ass ass 
        ON ass.AssocID = lb.AssocID 
JOIN
    lockbox.LBNames lbnm 
        ON lbnm.TopAssembly = mfg.TopAssembly 
GROUP BY
    ass.Name,
    lbnm.ProductName 
ORDER BY
    NULL

Related Articles



* original question posted on StackOverflow here.