Wednesday, August 19, 2015

Query Hints

(Source: msdn.microsoft.com)

Query hints specify that the indicated hints should be used throughout the query. They affect all operators in the statement. If UNION is involved in the main query, only the last query involving a UNION operation can have the OPTION clause. Query hints are specified as part of the OPTION clause. If one or more query hints cause the query optimizer not to generate a valid plan, error 8622 is raised. Because the SQL Server query optimizer typically selects the best execution plan for a query, we recommend only using hints as a last resort for experienced developers and database administrators.
Query hints cannot be specified in an INSERT statement except when a SELECT clause is used inside the statement. Query hints can be specified only in the top-level query, not in subqueries. When a table hint is specified as a query hint, the hint can be specified in the top-level query or in a subquery;

When specified as a query hint, the INDEX, FORCESCAN, and FORCESEEK table hints are valid for the following objects:
  • Tables
  • Views
  • Indexed views
  • Common table expressions (the hint must be specified in the SELECT statement whose result set populates the common table expression)
  • Dynamic management views
  • Named subqueries

The INDEX, FORCESCAN, and FORCESEEK table hints can be specified as query hints for a query that does not have any existing table hints, or they can be used to replace existing INDEX, FORCESCAN or FORCESEEK hints in the query, respectively. Table hints other than INDEX, FORCESCAN, and FORCESEEK are disallowed as query hints unless the query already has a WITH clause specifying the table hint. In this case, a matching hint must also be specified as a query hint by using TABLE HINT in the OPTION clause to preserve the semantics of the query. When a table hint other than INDEX, FORCESCAN, or FORCESEEK is specified by using TABLE HINT in the OPTION clause without a matching query hint, or vice versa; error 8702 is raised and the query fails.

Examples:
OPTION (MERGE JOIN)
OPTION (MAXRECURSION 2)
OPTION (MERGE UNION)
OPTION (MAXDOP 2)
OPTION (TABLE HINT(e, INDEX(PK_Employee_EmployeeID, IX_Employee_ManagerID)))

OPTION (TABLE HINT( HumanResources.Employee, FORCESEEK))

No comments:

Post a Comment