Указания (Transact-SQL)
Подсказки являются параметрами или стратегиями, указанными для обеспечения выполнения инструкций SELECT, INSERT, UPDATE или DELETE обработчиком запросов SQL Server. Указания имеют преимущество над любым планом выполнения, который может быть выбран оптимизатором запросов для запроса.
Так как оптимизатор запросов SQL Server обычно выбирает наилучший план выполнения для запроса, рекомендуется использовать , и в последнюю очередь и только опытным разработчикам и администраторам баз данных.
В этом разделе описаны следующие указания:
- Указания в соединении
- Указания запросов
- Табличное указание
Обратная связь
Были ли сведения на этой странице полезными?
Что такое хинты в T-SQL (Microsoft SQL Server)
Приветствую Вас на сайте Info-Comp.ru! В данном материале мы с Вами поговорим о том, что же такое хинты в языке T-SQL (Microsoft SQL Server), Вы узнаете, какие типы хинтов бывают, для чего и в каких случаях мы их можем использовать.
В предыдущих материалах мы с Вами рассмотрели архитектуру выполнения запроса в Microsoft SQL Server, план выполнения запроса, поговорили об операторах плана запроса, сегодня же мы поговорим о том, как мы можем влиять на процесс формирования плана выполнения запроса, а влиять на него мы можем как раз с помощью хинтов.
- Архитектура обработки SQL запросов в Microsoft SQL Server
- План выполнения запроса в Microsoft SQL Server – что это такое и для чего он нужен
- Описание операторов плана выполнения запроса в Microsoft SQL Server
Хинты в T-SQL
Хинт (hint) – это указание оптимизатору запросов, которое переопределяет его поведение по умолчанию на время выполнения SQL инструкции.
Иными словами, с помощью хинта мы можем сказать оптимизатору запросов, как именно поступить в той или иной ситуации в процессе построения плана запроса.
Например, мы можем сказать, какой конкретно индекс использовать, какой конкретно алгоритм физического соединения таблиц применить, или, допустим, на время выполнения запроса разрешить «грязное чтение».
Обычно оптимизатор запросов SQL Server выбирает самый оптимальный план выполнения запроса и крайне редко ошибается, поэтому использовать подсказки, т.е. хинты, без острой на то необходимости не рекомендуется.
Однако оптимизатор запросов все же может ошибиться или построить план, который нас будет не устраивать, и в этом случае мы можем подсказать оптимизатору с помощью хинтов, как лучше было бы поступить в той или иной ситуации.
Обязательно стоит отметить, при использовании хинтов Вы должны четко понимать, как изменится план выполнения запроса и как запрос с хинтом будет отрабатывать в случае изменения каких-либо факторов, которые влияют на процесс формирования плана. Например, что будет, если у нас объем данных в таблицах, участвующих в запросе, увеличится в несколько раз, т.е. в данном случае Вы должны понимать, не просядет ли производительность с нашим хинтом в случае увеличения объема данных, иными словами, наш хинт так же эффективно будет работать, как и с текущим объемом данных.
Примечание! Факторов, влияющих на построение плана выполнения запроса, на самом деле много, поэтому использование хинтов рекомендуется только опытным разработчикам и администраторам баз данных, да и то в самом крайнем случае, когда другого решения нет.
Типы хинтов в T-SQL
В Microsoft SQL Server хинты мы можем использовать в разных секциях запроса, и на основе этого можно выделить следующие типы хинтов.
Using Hints in SQL Statements
Hints are instructions that you place within a SQL statement that tell the data source query optimizer the most efficient way to execute the statement.
Hints override the optimizer’s execution plan, so you can use hints to improve performance by forcing the optimizer to use a more efficient plan. Hints are only supported for Oracle Database data sources.
Using the Administration Tool , you can add hints to a repository, in both online and offline modes, to optimize the performance of queries. When you add a hint to the repository, you associate it with Physical layer objects. When the object associated with the hint is queried, the Oracle BI Server inserts the hint into the SQL statement.
The table shows the physical objects with which you can associate hints. It also shows the Administration Tool dialog that corresponds to the physical object. Each of these dialogs contains a Hint field, into which you can type a hint to add it to the repository.
Physical foreign key
Physical Foreign Key
Physical Table — General tab
Hints are only supported when the Table Type is set to Physical Table . For other table types, the hint text is ignored. For physical tables with a table type of Select , you can provide the hint text as part of the SQL statement entered in the Default Initialization String field.
How to Use Oracle Hints
Learn how to use Oracle hints with the Oracle BI Server.
For more information about Oracle hints, see SQL r eference guide for the version of the Oracle Database that you use.
This section contains the following topics:
- About the Index Hint
- About the Leading Hint
About the Index Hint
The Index hint explains how the optimizer scans a specified index rather than a table.
If queries against the ORDER_ITEMS table are slow, you can review the execution plan of the query optimizer. If the FAST_INDEX was not used, you can create an Index hint to force the optimizer to scan the FAST_INDEX rather than the ORDER_ITEMS table. The syntax for the Index hint is as follows:
index( table_name , index_name )
To add this hint to the repository, open the Physical Table dialog in the Administration Tool , and type the following text in the Hint field:
index(ORDER_ITEMS, FAST_INDEX)
About the Leading Hint
The Leading hint forces the optimizer to build the join order of a query with a specified table.
The syntax for the Leading hint is leading( table_name ) . If you were creating a foreign key join between the Products table and the Sales Fact table and wanted to force the optimizer to begin the join with the Products table, you would go to the Physical Foreign Key dialog in the Administration Tool and type the following text in the Hint field:
leading(Products)
About Performance Considerations for Hints
Hints that are well researched and planned can result in significantly better query performance.
However, hints can also negatively affect performance if they result in a suboptimal execution plan.
Follow these guidelines to create hints to optimize query performance:
- Only add hints to a repository after you have tried to improve performance in the following ways:
- Added physical indexes or other physical changes to the Oracle Database.
- Made modeling changes within the server.
Creating Hints
You can add hints to the repository using the Oracle BI Administration Tool.
To create a hint:
- In the Administration Tool , go to one of the following dialogs:
- Physical Table—General tab
- Physical Foreign Key
- Complex Join
For a description of available Oracle hints and hint syntax, see SQL reference for the version of the Oracle Database that you use.
Note: Although hints are identified using SQL comment markers (/* or —), do not type SQL comment markers when you type the text of the hint. The Oracle BI Server inserts the comment markers when the hint is executed.
Hints
Hints are directives that you embed within a query or directed query. They conform to the following syntax:
/*+ hint-name[, hint-name]. */
Hints are bracketed by comment characters /*+ and */ , which can enclose multiple comma-delimited hints. For example:
/*+ DIRECT, LABEL(myLabel) */
Restrictions
When embedding hints, be aware of the following restrictions:
- Do not embed spaces in the comment characters /* and */ .
- In general, spaces are allowed before and after the plus ( + ) character and hint‑name ; however, some third-party tools do not support spaces embedded inside /* +.
Supported Hints
Vertica supports the following hints:
General hints ALLNODES Qualifies an EXPLAIN statement to request a query plan that assumes all nodes are active. EARLY_MATERIALIZATION Specifies early materialization of a table for the current query. ENABLE_WITH_CLAUSE_MATERIALIZATION Enables and disables WITH clause materialization for a specific query. LABEL Labels a query so you can identify it for profiling and debugging. SKIP_STATISTICS Directs the optimizer to produce a query plan that incorporates only minimal statistics. Eon Mode hints DEPOT_FETCH Specifies whether a query fetches data to the depot from communal storage when the depot lacks data for this query. ECSMODE Specifies the strategy to use when dividing data in a shard among is subscribers in a subcluster using ECS. See Manually Choosing an ECS Strategy for more information. Join hints SYNTACTIC_JOIN Enforces join order and enables other join hints. DISTRIB Sets the input operations for a distributed join to broadcast, resegment, local, or filter. GBYTYPE Specifies which algorithm— GROUPBY HASH or GROUPBY PIPELINED —the Vertica query optimizer should use to implement a GROUP BY clause. JTYPE Enforces the join type: merge or hash join. UTYPE Specifies how to combine UNION ALL input. Table hints PROJS Specifies one or more projections to use for a queried table. SKIP_PROJS Specifies which projections to avoid using for a queried table. Directed query hints IGNORECONST Maps an input query constant to one or more annotated query constants. VERBATIM Enforces execution of an annotated query exactly as written.
