[Solved] Possible causes that a MySQL/MariaDB query is slow under some table conditions

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: 57): 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 `products_options_values_id` is indexed, the index won’t be used as it’s wrapped with the function `Concat`. 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. Avoid Correlated Subqueries (query line: 8): A correlated subquery is a subquery that contains a reference (column: products_id) 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 Subqueries (query line: 13): We advise against using subqueries as they are not optimized well by the optimizer. Therefore, it's recommended to join a newly created temporary table that holds the data, which also includes the relevant search index.
  4. 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.
  5. Use Numeric Column Types For Numeric Values (query line: 53): 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: 47): 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 `products` ADD INDEX `products_idx_products_status_products_added` (`products_status`,`products_date_added`);
ALTER TABLE `products_attributes` ADD INDEX `products_attribute_idx_options_id_products_options_id` (`options_id`,`products_id`,`options_values_id`);
ALTER TABLE `products_description` ADD INDEX `products_descripti_idx_products_id` (`products_id`);
ALTER TABLE `products_options_values` ADD INDEX `products_values_idx_products_order` (`products_options_values_sort_order`);
ALTER TABLE `products_options_values` ADD INDEX `products_values_idx_language_id_products_id` (`language_id`,`products_options_values_id`);
ALTER TABLE `products_stock` ADD INDEX `products_stock_idx_products_id_products_quanti` (`products_id`,`products_stock_quantity`);
ALTER TABLE `specials` ADD INDEX `specials_idx_products_id` (`products_id`);
The optimized query:
SELECT
        DISTINCT pav.products_options_values_id,
        pav.products_options_values_name,
        pav.products_options_values_sort_order 
    FROM
        products_stock ps,
        products_options_values pav,
        (SELECT
            DISTINCT pa.products_id 
        FROM
            products_attributes pa,
            products_options_values pov,
            (SELECT
                p.products_id,
                p.products_image,
                p.products_subimage1,
                pd.products_name,
                p.products_quantity,
                p.products_model,
                p.products_ordered,
                p.products_price,
                p.products_date_added,
                p.products_weight,
                p.products_length,
                p.products_width,
                p.products_height,
                p.products_tax_class_id,
                p.products_status,
                IF(s.status,
                s.specials_new_products_price,
                NULL) AS specials_new_products_price,
                IF(s.status,
                s.specials_new_products_price,
                p.products_price) AS final_price,
                IF(p.clearance_price < p.products_cost * 2.25,
                p.clearance_price,
                p.products_cost * 2.25) AS sorting_price 
            FROM
                products p 
            LEFT JOIN
                specials s 
                    ON p.products_id = s.products_id 
            LEFT JOIN
                products_description pd 
                    ON p.products_id = pd.products_id 
            WHERE
                p.products_status = '1' 
                AND Date_sub('2016-04-19', INTERVAL 7000 day) <= p.products_date_added) m 
        WHERE
            m.products_id = pa.products_id 
            AND pa.options_id = 1 
            AND pa.options_values_id = pov.products_options_values_id 
            AND pov.language_id = '1'
        ) q 
    WHERE
        q.products_id = ps.products_id 
        AND ps.products_stock_attributes = Concat('1-', pav.products_options_values_id) 
        AND ps.products_stock_quantity > 0 
    ORDER BY
        pav.products_options_values_sort_order ASC

Related Articles



* original question posted on StackOverflow here.