Microsoft KB Archive/46434

= INFO: Writing Efficient Queries and Stored Procedures =

Article ID: 46434

Article Last Modified on 3/2/2005

-

APPLIES TO


 * Microsoft SQL Server 4.21a Standard Edition

-



This article was previously published under Q46434



SUMMARY
This article contains some suggestions for writing efficient queries and stored procedures.



MORE INFORMATION
WHERE clauses that direct the index and join order selection should be of the following form:

    AND... (all cols from same table) AND... (join criteria) OR...

WHERE clauses containing NOT are not useful to the optimizer for index selection. Indexes that consist of several columns are useful only if the selection columns comprise a prefix of the index (or completely match the index).

The &quot;=&quot; (equals) sign is best if a unique index is available. Closed ranges are next ( col1>5 AND col1<10 ); open intervals are next ( c1>5 ).

Higher priority will be given to indexes that &quot;cover&quot; the query (include all of the columns in the select list) because it is then no longer necessary to access the actual data pages.

Do not use expressions or data conversions in index and join-selection WHERE clauses or the optimizer may not recognize that the expression evaluates to a constant.

Local variables in WHERE clauses are considered to be &quot;unknown&quot; and are not considered by the optimizer, except for the input parameters of stored procedures.

In versions of SQL Server earlier than 4.2, subqueries are &quot;unwound&quot; into joins by the optimizer. This can introduce duplicates in certain self-joins unless &quot;DISTINCT&quot; is added (prior to version 4.2).

IN lists are treated as multiple OR clauses. BETWEEN is treated as a closed interval. LIKE with a trailing wild card is treated as a closed interval.

Be sure your STATISTICS are up-to-date. Remember that stored procedures are not re-optimized when indexes are added.

SET STATISTICS I/O & TIME ON and SET SHOWPLAN ON can help in understanding what the optimizer is doing when processing a particular query or procedure.

Output from SET SHOWPLAN ON
Table scan means no index was used and the data pages were blind-searched. The alternative is &quot;index n used&quot; or something similar. If there was an index that could have been used and wasn't, run UPDATE STATISTICS.

Nested Iteration is the default join technique. The critical performance consideration is the order of nesting. The best order is that which minimizes physical I/O. The alternative join technique is &quot;reformat,&quot; which is really a match/merge.

The term &quot;Vector aggregate&quot; is an aggregate function that produces multiple values instead of just one like &quot;sum.&quot;

Additional query words: 4.20 4.2a 4.2b 4.21 Optimization Tuning

Keywords: kbinfo kbusage KB46434

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.