[Solved] SQL: 1=1 performance hit

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: 24): 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 `col3` is indexed, the index won’t be used as it’s wrapped with the function `fun1`. 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: 47): A correlated subquery is a subquery that contains a reference (column: Item) 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 LIKE Searches With Leading Wildcard (query line: 105): The database will not use an index when using like searches with a leading wildcard (e.g. '%'). Although it's not always a satisfactory solution, please consider using prefix-match LIKE patterns (e.g. 'TERM%').
  4. Avoid Selecting Unnecessary Columns (query line: 5): Avoid selecting all columns with the '*' wildcard, unless you intend to use them all. Selecting redundant columns may result in unnecessary performance degradation.
  5. Avoid Subqueries (query line: 4): 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.
  6. 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.
  7. Use Numeric Column Types For Numeric Values (query line: 24): 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:
CREATE INDEX tab1_idx_col1 ON tab1 (col1);
CREATE INDEX tab2_idx_col2 ON tab2 (col2);
The optimized query:
SELECT
        * 
    FROM
        (SELECT
            Alls.*,
            ROW_NUMBER() OVER (ORDER 
        BY
            Alls.col1 DESC) AS RowNum,
            COUNT(*) OVER () AS TotalCount 
        FROM
            tab1 AllS 
        LEFT JOIN
            tab2 FF 
                ON Alls.col2 = FF.col2 
        WHERE
            (
                (
                    (
                        @par1 IS NULL 
                        AND 1 = 1
                    ) 
                    OR (
                        @par1 IS NOT NULL 
                        AND '1' = fun1(col3, ',', @par1, 'exact contains')
                    )
                ) 
                AND (
                    (
                        @par2 IS NULL 
                        AND 1 = 1
                    ) 
                    OR (
                        @par2 IS NOT NULL 
                        AND (
                            Alls.col1 BETWEEN CONVERT(DATETIME, @par2) AND CONVERT(DATETIME, @par7)
                        )
                    )
                ) 
                AND (
                    (
                        @par3 IS NULL 
                        AND 1 = 1
                    ) 
                    OR (
                        @par3 IS NOT NULL 
                        AND col4 IN (
                            SELECT
                                CONVERT(INT,
                                Item) 
                            FROM
                                dbo.Split(@par3,
                                ',')
                        )
                    )
                ) 
                AND (
                    (
                        (
                            @par4 IS NULL 
                            AND col5 = NULL
                        ) 
                        OR (
                            @par4 IS NOT NULL 
                            AND col5 = @par4
                        )
                    ) 
                    OR (
                        (
                            @par5 IS NULL 
                            AND col6 = NULL
                        ) 
                        OR (
                            @par5 IS NOT NULL 
                            AND col6 = @par5
                        )
                    ) 
                    OR (
                        (
                            @par6 IS NULL 
                            AND col7 = NULL
                        ) 
                        OR (
                            @par6 IS NOT NULL 
                            AND col7 = @par6
                        )
                    ) 
                    AND (
                        (
                            @par8 IS NULL 
                            AND 1 = 1
                        ) 
                        OR (
                            @par8 IS NOT NULL 
                            AND col8 IS NULL
                        )
                    ) 
                    AND (
                        (
                            (
                                @par9 IS NULL 
                                AND 1 = 1
                            ) 
                            OR (
                                @par9 IS NOT NULL 
                                AND col9 LIKE '%' + @par9 + '%'
                            )
                        ) 
                        OR (
                            (
                                @par9 IS NULL 
                                AND 1 = 1
                            ) 
                            OR (
                                @par9 IS NOT NULL 
                                AND col8 = @par9
                            )
                        )
                    )
                )
            ) 
            AND col10 = 1 
            AND col11 IS NULL
        ) AS List 
    WHERE
        RowNum BETWEEN @startRowIndex AND (
            @startRowIndex + @pageSize
        ) - 1 
    ORDER BY
        List.col1 DESC

Related Articles



* original question posted on StackOverflow here.