[Solved] Merge Rows Together wth same ID SQL Server

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 Correlated Subqueries (query line: 26): A correlated subquery is a subquery that contains a reference (column: list) 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.
  2. Avoid Correlated Subqueries (query line: 54): A correlated subquery is a subquery that contains a reference (column: Tag) 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 Correlated Subqueries (query line: 64): A correlated subquery is a subquery that contains a reference (column: BusinessRuleSegmentID) 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.
  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. Remove Redundant Left Joins (modified query below): Redundant LEFT JOINs (e.g. `BMT_MappingRuleServiceType`) were detected in the query. Removing them will result in a performance improvement. In some cases, JOINs become redundant after an optimization is applied, such as when converting OR conditions to a UNION clause.
Optimal indexes for this query:
CREATE INDEX bmt_businessrulece_idx_businessrulesegmentid ON BMT_BusinessRuleCell (BusinessRuleSegmentID);
CREATE INDEX bmt_businessrulece_idx_businessrulecellid ON BMT_BusinessRuleCellOption (BusinessRuleCellId);
CREATE INDEX bmt_businessrulecr_idx_businessrulecriteriaid ON BMT_BusinessRuleCriteria (BusinessRuleCriteriaID);
CREATE INDEX bmt_businessrulese_idx_businessrulecriteriaid ON BMT_BusinessRuleSegment (BusinessRuleCriteriaID);
CREATE INDEX bmt_businessrulese_idx_businessrulesegmentid ON BMT_BusinessRuleSegmentTag (BusinessRuleSegmentID);
The optimized query:
SELECT
        ESTable.[BusinessRuleCriteriaID],
        ESTable.[ItemType],
        ESTable.[tag],
        ESTable.[TagValue],
        ESTable.Operator,
        [ESSubTag],
        ESTable.[ES01],
        ESTable.[ES02],
        ESTable.[ES03],
        ESTable.[ES04],
        ESTable.[ES05],
        ESTable.[ES06],
        ESTable.[ES07],
        ESTable.[ES08],
        ESTable.[ES09],
        ESTable.[ES10],
        ESTable.[ES11],
        ESTable.[ES12],
        ESTable.[ITMSubTag],
        ESTable.[ITM01],
        [RR4SubTag],
        ESTable.[RR401],
        ESTable.[RR402] 
    FROM
        (SELECT
            DISTINCT crit.BusinessRuleCriteriaID,
            crit.ItemType,
            crit.tag,
            crit.TagValue,
            crit.Operator,
            CASE 
                WHEN seg.SegmentType = 'ES' THEN SegSubTags.list END AS [ESSubTag],
CASE 
    WHEN seg.SegmentType = 'ITM' THEN SegSubTags.list END AS [ItemSubTag],
CASE 
    WHEN seg.SegmentType = 'RR4' THEN SegSubTags.list END AS [RR4SubTag],
c.CellName AS [SegmentId],
CASE 
    WHEN c.CellValue IS NOT NULL 
    AND len(c.CellValue) > 0 THEN c.CellValue 
    ELSE ItemTagDescriptions.list END AS [Tags] 
FROM
BMT_BusinessRuleCriteria crit 
LEFT OUTER JOIN
BMT_BusinessRuleSegment seg 
    ON seg.BusinessRuleCriteriaID = crit.BusinessRuleCriteriaID 
LEFT OUTER JOIN
BMT_BusinessRuleCell c 
    ON c.BusinessRuleSegmentID = seg.BusinessRuleSegmentID 
LEFT OUTER JOIN
BMT_BusinessRuleCellOption MT 
    ON c.BusinessRuleCellId = MT.BusinessRuleCellId 
OUTER APPLY (SELECT
IsNull(MT2.Tag,
'{Unknown}') + ISNULL('=' + MT.TagValue,
'') + ':' + IsNull(MT.CellValue,
'') + ';' AS [text()] FROM
    BMT_BusinessRuleCellOption MT 
WHERE
    MT.BusinessRuleCellId = MT.BusinessRuleCellId 
ORDER BY
    MT.BusinessRuleCellId FOR XML PATH('')) ItemTagDescriptions(list) 
OUTER APPLY (SELECT
IsNull(SegSubTag.Tag,
'{Unknown}') + ' ' + ISNULL(SegSubTag.Operator,
'') + ' ' + IsNull(SegSubTag.TagValue,
'') + ';' AS [text()] FROM
    BMT_BusinessRuleSegmentTag SegSubTag 
WHERE
    SegSubTag.BusinessRuleSegmentID = seg.BusinessRuleSegmentID 
ORDER BY
    SegSubTag.BusinessRuleSegmentID FOR XML PATH('')) SegSubTags(list) 
WHERE
crit.BusinessRuleCriteriaID = 489302
) AS ESTable PIVOT (max([Tags]) FOR [SegmentId] IN ([ES01], [ES02], [ES03], [ES04], [ES05], [ES06], [ES07], [ES08], [ES09], [ES10], [ES11], [ES12], [ITM01], [RR401], [RR402])) AS ESPivotTable

Related Articles



* original question posted on StackOverflow here.