How to Tune SQL Statement with OR conditions in a Subquery for SQL Server?

Discussion in 'SQL Server' started by Richard To, Jun 1, 2021.

  1. Richard To

    Richard To Member

    Joined:
    Sep 18, 2017
    Messages:
    87
    Likes Received:
    36
    Trophy Points:
    18
    Gender:
    Male
    The following is an example that shows a SQL statement with an EXISTS subquery. The SQL counts the records from the EMPLOYEE table if the OR conditions are satisfied in the subquery of the DEPARTMENT table.

    select countn(*) from employee a where
    exists (select 'x' from department b
    where a.emp_id=b.dpt_manager or a.emp_salary=b.dpt_avg_salary)​

    Here the following is the query plan in the Tosska proprietary tree format, it takes 4 minutes and 29 seconds to finish.
    [​IMG]
    The query plan shows a Nested Loops from EMPLOYEE to full table scan DEPARTMENT, it is the main problem of the entire query plan, the reason is the SQL Server cannot resolve this OR conditions ”a.emp_id=b.dpt_manager or a.emp_salary=b.dpt_avg_salary” by other join operations.

    Let me rewrite the OR conditions in the subquery into a UNION ALL subquery in the following, the first part of the UNION ALL in the subquery represents the “a.emp_id=b.dpt_manager” condition, the second part represents the “a.emp_salary=b.dpt_avg_salary” condition but exclude the data that already satisfied with the first condition.

    select count(*)
    from employee a
    where exists ( select 'x'
    from department b
    where a.emp_id = b.dpt_manager
    union all
    select 'x'
    from department b
    where (not ( a.emp_id = b.dpt_manager )
    or b.dpt_manager is null )
    and a.emp_salary = b.dpt_avg_salary )​

    Here the following is the query plan of the rewritten SQL, it looks a little bit complex, but the performance is very good now, it takes only 0.447 seconds. There are two Hash Match joins that are used to replace the original Nested Loops from EMPLOYEE to full table scan DEPARTMENT.
    [​IMG]
    Although the steps to the final rewrite is a little bit complicated, this kind of rewrites can be achieved by Tosska SQL Tuning Expert for SQL Server automatically, it shows that the rewrite is more than 600 times faster than the original SQL.

    Tosska SQL Tuning Expert (TSES™) for SQL Server® - Tosska Technologies Limited
    [​IMG]
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice