[Solved] Pivoting in SQL Combining two Columns

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.
Optimal indexes for this query:
ALTER TABLE `aud_bat_t` ADD INDEX `aud_t_idx_tmp_id` (`tmp_id`);
ALTER TABLE `lg_clmn_t` ADD INDEX `lg_t_idx_lg_id` (`lg_col_id`);
ALTER TABLE `stats_dtl_t` ADD INDEX `stats_t_idx_batch_id` (`batch_id`);
ALTER TABLE `templ_t` ADD INDEX `templ_t_idx_tmplt_id` (`tmplt_id`);
The optimized query:
SELECT
        sb.col_nm + '.' + sb.col_r_nm AS 'Combined',
        mt.vlu_cd,
        at.tmplt_id 
    FROM
        templ_t at 
    INNER JOIN
        aud_bat_t b 
            ON b.tmp_id = at.tmp_id 
    INNER JOIN
        stats_dtl_t mt 
            ON mt.batch_id = b.batch_id 
    INNER JOIN
        lg_clmn_t sb 
            ON sb.lg_col_id = mt.lg_col_id 
    WHERE
        at.tmplt_id = 6 
    ORDER BY
        sb.col_nm + '.' + sb.col_r_nm,
        mt.vlu_cd,
        at.tmplt_id

Related Articles



* original question posted on StackOverflow here.