[Solved] make queries using CASE WHEN faster

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 OR Conditions By Using UNION (modified query below): In mosts cases, filtering using the OR operator cannot be applied using indexes. A more optimized alternative will be to split the query to two parts combined with a UNION clause, while each query holds one part of the original OR condition.
  2. Avoid Subqueries (query line: 23): 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.
  3. Avoid Subqueries (query line: 102): 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. Prefer Inner Join Over Left Join (modified query below): We identified that one or more left joined entities (e.g. `oc_product`) are used in the 'where' clause, in a way that allows to replace it with an optimized inner join. Inner joins can be fully optimized by the database, while Left joins apply limitations on the database's optimizer.
  6. Prefer Inner Join Over Left Join (modified query below): We identified that one or more left joined entities (e.g. `oc_order`) are used in the 'where' clause, in a way that allows to replace it with an optimized inner join. Inner joins can be fully optimized by the database, while Left joins apply limitations on the database's optimizer.
  7. Use Numeric Column Types For Numeric Values (query line: 83): Referencing a numeric value (e.g. 0) 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.
  8. Use Numeric Column Types For Numeric Values (query line: 84): Referencing a numeric value (e.g. 5) 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.
  9. Use Numeric Column Types For Numeric Values (query line: 38): Referencing a numeric value (e.g. 0) 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.
  10. Use Numeric Column Types For Numeric Values (query line: 150): Referencing a numeric value (e.g. 0) 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.
  11. Use Numeric Column Types For Numeric Values (query line: 151): Referencing a numeric value (e.g. 5) 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.
  12. Use Numeric Column Types For Numeric Values (query line: 117): Referencing a numeric value (e.g. 0) 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.
  13. Use UNION ALL instead of UNION (query line: 91): 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 `oc_manufacturer` ADD INDEX `oc_manufacturer_idx_manufacturer_id` (`manufacturer_id`);
ALTER TABLE `oc_order` ADD INDEX `oc_order_idx_order_id_date_added` (`order_status_id`,`date_added`);
ALTER TABLE `oc_order_product` ADD INDEX `oc_product_idx_order_id` (`order_id`);
ALTER TABLE `oc_product` ADD INDEX `oc_product_idx_product_id` (`product_id`);
ALTER TABLE `oc_stock_kps` ADD INDEX `oc_kps_idx_product_id_order_id` (`product_id`,`order_id`);
ALTER TABLE `oc_stock_kps` ADD INDEX `oc_kps_idx_buy_price` (`buy_price`);
ALTER TABLE `oc_stock_kps` ADD INDEX `oc_kps_idx_id` (`id`);
ALTER TABLE `product_to_category` ADD INDEX `product_category_idx_category_id_product_id` (`category_id`,`product_id`);
The optimized query:
SELECT
        t1_date_added,
        t1_order_id,
        customer,
        product_name,
        t1_category,
        t1_supplier,
        t1_quantity,
        t1_price,
        t1_total 
    FROM
        ((SELECT
            t1.date_added AS t1_date_added,
            t1.order_id AS t1_order_id,
            t1.firstname AS customer,
            t1.name AS product_name,
            t1.category AS t1_category,
            t1.supplier AS t1_supplier,
            t1.quantity AS t1_quantity,
            t1.price AS t1_price,
            t1.total AS t1_total 
        FROM
            (SELECT
                o.date_added,
                op.order_id,
                o.firstname,
                op.name,
                op.price,
                op.total,
                op.quantity,
                m.name AS supplier,
                (CASE 
                    WHEN skps.buy_price IS NULL THEN (SELECT
                        skps2.buy_price 
                    FROM
                        `oc_stock_kps` skps2 
                    WHERE
                        skps2.buy_price != '0' 
                    ORDER BY
                        skps2.id DESC LIMIT 1) 
                    ELSE skps.buy_price END) AS buy_price,
(SELECT
    GROUP_CONCAT(cd.name SEPARATOR ' / ') 
FROM
    oc_category_description cd 
LEFT JOIN
    product_to_category ptc 
        ON (
            ptc.category_id = cd.category_id
        ) 
WHERE
    ptc.product_id = p.product_id) AS category,
LAG(op.name) OVER (ORDER 
BY
op.order_product_id) prev 
FROM
`oc_order_product` op 
INNER JOIN
oc_order o 
    ON (
        op.order_id = o.order_id
    ) 
INNER JOIN
oc_product p 
    ON (
        op.product_id = p.product_id
    ) 
LEFT JOIN
oc_manufacturer m 
    ON (
        p.manufacturer_id = m.manufacturer_id
    ) 
LEFT JOIN
oc_stock_kps skps 
    ON (
        skps.product_id = op.product_id 
        AND skps.order_id = op.order_id
    ) 
WHERE
(
    o.date_added BETWEEN '2021-02-01 00:00:00' AND '2021-02-28 23:59:00'
) 
AND p.product_id != '0' 
AND o.order_status_id = '5'
) t1 
WHERE
t1.name <> t1.prev 
ORDER BY
t1.date_added LIMIT 12) 
UNION
DISTINCT (SELECT
t1.date_added AS t1_date_added,
t1.order_id AS t1_order_id,
t1.firstname AS customer,
t1.name AS product_name,
t1.category AS t1_category,
t1.supplier AS t1_supplier,
t1.quantity AS t1_quantity,
t1.price AS t1_price,
t1.total AS t1_total 
FROM
(SELECT
o.date_added,
op.order_id,
o.firstname,
op.name,
op.price,
op.total,
op.quantity,
m.name AS supplier,
(CASE 
    WHEN skps.buy_price IS NULL THEN (SELECT
        skps2.buy_price 
    FROM
        `oc_stock_kps` skps2 
    WHERE
        skps2.buy_price != '0' 
    ORDER BY
        skps2.id DESC LIMIT 1) 
    ELSE skps.buy_price END) AS buy_price,
(SELECT
    GROUP_CONCAT(cd.name SEPARATOR ' / ') 
FROM
    oc_category_description cd 
LEFT JOIN
    product_to_category ptc 
        ON (ptc.category_id = cd.category_id) 
WHERE
    ptc.product_id = p.product_id) AS category,
LAG(op.name) OVER (ORDER 
BY
op.order_product_id) prev 
FROM
`oc_order_product` op 
INNER JOIN
oc_order o 
    ON (op.order_id = o.order_id) 
INNER JOIN
oc_product p 
    ON (op.product_id = p.product_id) 
LEFT JOIN
oc_manufacturer m 
    ON (p.manufacturer_id = m.manufacturer_id) 
LEFT JOIN
oc_stock_kps skps 
    ON (skps.product_id = op.product_id 
    AND skps.order_id = op.order_id) 
WHERE
(o.date_added BETWEEN '2021-02-01 00:00:00' AND '2021-02-28 23:59:00') 
AND p.product_id != '0' 
AND o.order_status_id = '5') t1 
WHERE
t1.prev IS NULL 
ORDER BY
t1.date_added LIMIT 12)) AS union1 
ORDER BY
union1.t1_date_added LIMIT 12

Related Articles



* original question posted on StackOverflow here.