[Solved] SQL SD: Identify the most recent common past opponent between two teams

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 Calling Functions With Indexed Columns (query line: 23): When a function is used directly on an indexed column, the database's optimizer won’t be able to use the index. For example, if the column `GAME_DATE` is indexed, the index won’t be used as it’s wrapped with the function `ABS`. If you can’t find an alternative condition that won’t use a function call, a possible solution is to store the required value in a new indexed column.
  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.
Optimal indexes for this query:
CREATE INDEX team_1_idx_home_team_opp_team ON TEAM_SUMMARY_1 (HOME_TEAM,OPP_TEAM);
The optimized query:
SELECT
        A.GAME_DATE,
        A.GAME_NUMBER,
        A.INDEXING,
        A.HOME_TEAM,
        A.OPP_TEAM,
        B.OPP_TEAM AS SHARED_OPP,
        B.SCORE_DIFF AS OPP_SCORE_DIFF,
        C.SCORE_DIFF AS HOME_SCORE_DIFF,
        MIN((A.GAME_DATE - B.GAME_DATE) + (A.GAME_DATE - C.GAME_DATE) + ABS(B.GAME_DATE - C.GAME_DATE)) AS TOTAL_DATE_DIFF 
    FROM
        TEAM_SUMMARY_1 A 
    LEFT JOIN
        TEAM_SUMMARY_1 B 
            ON A.OPP_TEAM = B.HOME_TEAM 
    LEFT JOIN
        TEAM_SUMMARY_1 C 
            ON A.HOME_TEAM = C.HOME_TEAM 
    WHERE
        B.OPP_TEAM <> A.HOME_TEAM 
        AND A.OPP_TEAM <> C.OPP_TEAM 
        AND B.OPP_TEAM = C.OPP_TEAM 
        AND ABS(B.GAME_DATE - C.GAME_DATE) < 5 
        AND A.GAME_DATE - B.GAME_DATE < 20 
        AND A.GAME_DATE - B.GAME_DATE > 0 
        AND A.GAME_DATE - C.GAME_DATE < 20 
        AND A.GAME_DATE - C.GAME_DATE > 0 
    GROUP BY
        A.GAME_DATE,
        A.GAME_NUMBER,
        A.INDEXING,
        A.HOME_TEAM,
        A.OPP_TEAM,
        B.OPP_TEAM,
        B.SCORE_DIFF,
        C.SCORE_DIFF 
    ORDER BY
        A.GAME_DATE,
        A.HOME_TEAM,
        A.OPP_TEAM

Related Articles



* original question posted on StackOverflow here.