[Solved] Using some column data for values and some for ID

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. Prefer Sorting/Grouping By The First Table In Join Order (modified query below): The database can use indexes more efficiently when sorting and grouping using columns from the first table in the join order. The first table is determined based on the prediction of the the optimal first table, and is not necessarily the first table shown in the FROM clause.
Optimal indexes for this query:
ALTER TABLE `tbl_category` ADD INDEX `tbl_category_idx_category_id` (`category_id`);
ALTER TABLE `tbl_program` ADD INDEX `tbl_program_idx_progra_name_copyri_active_parent` (`program_id`,`name`,`copyright`,`active_flag`,`parent_program_id`);
ALTER TABLE `xref_category_program` ADD INDEX `xref_program_idx_category_id` (`category_id`);
The optimized query:
SELECT
        p.parent_program_id,
        p.program_id,
        p.name,
        p.copyright,
        p.active_flag,
        max(CASE 
            WHEN c.category_id = 36261 THEN 'X' 
            ELSE ' ' END) AS CC_Indicator,
max(CASE 
    WHEN c1.category_id = 36362 THEN 'X' 
    ELSE ' ' END) AS CC_Badge,
max(CASE 
    WHEN c2.category_id = 43221 THEN 'X' 
    ELSE ' ' END) AS CC_Solution 
FROM
tbl_program p 
JOIN
xref_category_program xcp 
    ON p.program_id = xcp.program_id 
LEFT JOIN
tbl_category c 
    ON xcp.category_id = c.category_id 
    AND c.category_id = 36261 
LEFT JOIN
tbl_category c1 
    ON xcp.category_id = c1.category_id 
    AND c1.category_id = 36362 
LEFT JOIN
tbl_category c2 
    ON xcp.category_id = c2.category_id 
    AND c2.category_id = 43221 
WHERE
xcp.category_id IN (
    36261, 36362, 43221
) 
GROUP BY
p.program_id,
p.name,
p.copyright,
p.active_flag,
p.parent_program_id 
ORDER BY
xcp.program_id

Related Articles



* original question posted on StackOverflow here.