Does the order of columns in a WHERE clause matter?

前端 未结 7 1650
-上瘾入骨i
-上瘾入骨i 2020-11-28 14:29

Does the order of the columns in a WHERE clause effect performance?

e.g.

Say I put a column that has a higher potential for uniqueness first or visa versa?

7条回答
  •  日久生厌
    2020-11-28 14:32

    For SQL Server 2000 / 20005 / 2008, the query optimizer usually will give you identical results no matter how you arrange the columns in the WHERE clause. Having said this, over the years of writing thousands of T-SQL commands I have found a few corner cases where the order altered the performance. Here are some characteristics of the queries that appeared to be subject to this problem:

    1. If you have a large number of tables in your query (10 or more).

    2. If you have several EXISTS, IN, NOT EXISTS, or NOT IN statements in your WHERE clause

    3. If you are using nested CTE's (common-table expressions) or a large number of CTE's.

    4. If you have a large number of sub-queries in your FROM clause.

    Here are some tips on trying to evaluate the best way to resolve the performance issue quickly:

    1. If the problem is related to 1 or 2, then try reordering the WHERE clause and compare the sub-tree cost of the queries in the estimated query plans.

    2. If the problem is related to 3 or 4, then try moving the sub-queries and CTE's out of the query and have them load temporary tables. The query plan optimizer is FAR more efficient at estimating query plans if you reduce the number of complex joins and sub-queries from the body of the T-SQL statement.

    3. If you are using temporary tables, then make certain you have specified primary keys for the temporary tables. This means avoid using SELECT INTO FROM to generate the table. Instead, explicitly create the table and specify a primary KEY before using an INSERT INTO SELECT statement.

    4. If you are using temporary tables and MANY processes on the server use temporary tables as well, then you may want to make a more permanent staging table that is truncated and reloaded during the query process. You are more likely to encounter disk contention issues if you are using the TempDB to store your working / staging tables.

    5. Move the statements in the WHERE clause that will filter the most data to the beginning of the WHERE clause. Please note that if this is your solution to the problem, then you will probably have poor performance again down the line when the query plan gets confused again about generating and picking the best execution plan. You are BEST off finding a way to reduce the complexity of the query so that the order of the WHERE clause is no longer relevant.

    I hope you find this information helpful. Good luck!

提交回复
热议问题