[Solved] Query sometimes hangs (but can be executed in less than 4s when run in parallel)

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 Selecting Unnecessary Columns (query line: 48): Avoid selecting all columns with the '*' wildcard, unless you intend to use them all. Selecting redundant columns may result in unnecessary performance degradation.
  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.
  3. 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'.
  4. Use Numeric Column Types For Numeric Values (query line: 9): Referencing a numeric value (e.g. 1) as a string in a WHERE clause might result in poor performance. Possible impacts of storing numbers as varchars: more space will be used, you won't be able to perform arithmetic operations, the data won't be self-validated, aggregation functions like SUM won't work, the output may sort incorrectly and more. If the column is numeric, remove the quotes from the constant value, to make sure a numeric comparison is done.
  5. Use Numeric Column Types For Numeric Values (query line: 22): Referencing a numeric value (e.g. 1) as a string in a WHERE clause might result in poor performance. Possible impacts of storing numbers as varchars: more space will be used, you won't be able to perform arithmetic operations, the data won't be self-validated, aggregation functions like SUM won't work, the output may sort incorrectly and more. If the column is numeric, remove the quotes from the constant value, to make sure a numeric comparison is done.
  6. Use Numeric Column Types For Numeric Values (query line: 40): Referencing a numeric value (e.g. 1) as a string in a WHERE clause might result in poor performance. Possible impacts of storing numbers as varchars: more space will be used, you won't be able to perform arithmetic operations, the data won't be self-validated, aggregation functions like SUM won't work, the output may sort incorrectly and more. If the column is numeric, remove the quotes from the constant value, to make sure a numeric comparison is done.
Optimal indexes for this query:
ALTER TABLE `tam_results_14` ADD INDEX `tam_14_idx_result_custome_team_id_territo` (`result_id`,`customer_id`,`team_id`,`territory_name`);
ALTER TABLE `tam_results_14` ADD INDEX `tam_14_idx_resul_custo_team_team_terri_speci` (`result_id`,`customer_id`,`team_id`,`team_name`,`territory_name`,`specialty`);
The optimized query:
WITH distinct_users_team_tbl AS (SELECT
        tam_results_14.team_id,
        count(DISTINCT tam_results_14.id) AS distinct_users_team,
        count(DISTINCT tam_results_14.id) FILTER (WHERE targeted_users > 0) AS targeted_distinct_users_team 
    FROM
        tam_results_14 
    WHERE
        tam_results_14.result_id = 201 
        AND tam_results_14.customer_id = '1' 
    GROUP BY
        tam_results_14.team_id 
    ORDER BY
        NULL), distinct_users_territory_tbl AS (SELECT
        tam_results_14.team_id,
        tam_results_14.territory_name,
        count(DISTINCT tam_results_14.id) AS distinct_users_territory,
        count(DISTINCT tam_results_14.id) FILTER (WHERE targeted_users > 0) AS targeted_distinct_users_territory 
    FROM
        tam_results_14 
    WHERE
        tam_results_14.result_id = 201 
        AND tam_results_14.customer_id = '1' 
    GROUP BY
        tam_results_14.team_id,
        tam_results_14.territory_name 
    ORDER BY
        NULL), distinct_users_specialty_tbl AS (SELECT
        tam_results_14.team_id,
        tam_results_14.team_name,
        tam_results_14.territory_name,
        tam_results_14.specialty,
        sum(tam) AS tam,
        sum(sam) AS sam,
        count(DISTINCT tam_results_14.id) AS distinct_users_specialty,
        count(DISTINCT tam_results_14.id) FILTER (WHERE targeted_users > 0) AS targeted_distinct_users_specialty 
    FROM
        tam_results_14 
    WHERE
        tam_results_14.result_id = 201 
        AND tam_results_14.customer_id = '1' 
    GROUP BY
        tam_results_14.team_id,
        tam_results_14.team_name,
        tam_results_14.territory_name,
        tam_results_14.specialty 
    ORDER BY
        NULL) SELECT
        * 
    FROM
        distinct_users_specialty_tbl 
    JOIN
        distinct_users_team_tbl 
            ON distinct_users_specialty_tbl.team_id = distinct_users_team_tbl.team_id 
    JOIN
        distinct_users_territory_tbl 
            ON distinct_users_specialty_tbl.team_id = distinct_users_territory_tbl.team_id 
            AND distinct_users_specialty_tbl.territory_name = distinct_users_territory_tbl.territory_name

Related Articles



* original question posted on StackOverflow here.