[Solved] Optimizing a Join

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'.
Optimal indexes for this query:
ALTER TABLE `def208` ADD INDEX `def208_idx_eid` (`eid`);
ALTER TABLE `i208` ADD INDEX `i208_idx_iid_eid` (`iid`,`eid`);
ALTER TABLE `my208` ADD INDEX `my208_idx_my_id_data_eid` (`my_id`,`data`,`eid`);
The optimized query:
SELECT
        co.id AS ID_Eid,
        co.email,
        def.def_medium AS def_Medium_def208,
        co.created AS Contact_Create_Date,
        my1.data AS PAW_ID,
        my.data AS Trial_Date,
        my2.data AS Upgrade_Date,
        MIN(my3.lastmod) AS Cancel_Date 
    FROM
        abc_emails.cid208 co 
    LEFT JOIN
        abc_emails.my208 my 
            ON my.eid = co.id 
            AND my.my_id = 581 
    LEFT JOIN
        abc_emails.my208 my1 
            ON my1.eid = my.eid 
            AND my1.my_id = 2765 
    LEFT JOIN
        abc_emails.my208 my2 
            ON my2.eid = my.eid 
            AND my2.my_id = 3347 
    LEFT JOIN
        abc__emails.my208 my3 
            ON my3.eid = my.eid 
            AND (
                my3.my_id = 417 
                AND my3.data = 'AB Deleted Account'
            ) 
    LEFT JOIN
        abc_emails.i208 i 
            ON i.eid = my.eid 
            AND i.iid = 22467 
    LEFT JOIN
        abc_emails.def208 def 
            ON def.eid = co.id 
    WHERE
        i.iid IS NULL 
    GROUP BY
        ID_Eid,
        co.email,
        def_Medium_def208,
        Contact_Create_Date,
        PAW_ID,
        Upgrade_Date 
    ORDER BY
        NULL

Related Articles



* original question posted on StackOverflow here.