SQL Server uses many techniques to optimize resource consumption:
- Query optimization based on syntax;
- Useless plan matching to avoid deep optimization of simple queries;
- Index and connection strategy according to the current distribution statistics;
- Multi-stage query optimization to control the optimization cost;
- Execute a plan buffer to avoid rebuilding the execution plan;
The above techniques are performed in the following order:
- parser;
- Algebraic device;
- query optimizer;
- Execution plan generation, buffer and hash plan generation;
- Query execution;
The order of execution is as follows:
First, the parser (parser)
When the query is committed, SQL Server passes it to the parser in the relational engine.
- Relational engine-responsible for parsing, name and type resolution, optimizing and executing queries according to query execution plan and requesting data from the storage engine;
- Storage Engine-responsible for data access, modification, buffering;
The parser checks the incoming query to verify that its syntax is correct. If a syntax error is found, the query is terminated. If multiple queries are committed together as a batch, as follows:
CREATE TABLE INT )INSERTintoVALUES(1* from T1 --Note that the Select spelling error GO
The parser checks the syntax of the entire batch and revokes the entire batch when a syntax error is found (multiple syntax errors may occur in the batch, but the parser does not continue after the first error, so there is a syntax error in the batch and the code is not executed on a single line. When validating the syntax of a query, the parser generates an internal data structure called the parse tree for the algebra. parsers and algebras are collectively referred to as query compilation.
two , algebraic Device (algebrizer)
The parse tree generated by the parser is passed to the Algebra processor. The Algebra parser parses all the names of different objects, the tables, columns, and so on that T-SQL refers to. It also confirms that all the different data types are processed and even checks the location of the aggregation (GROUP by, MAX). All of these validation and parsing outputs are binary datasets called query processor trees.
In order to understand the operation of the algebraic device, submit the following batch query:
CREATE TABLET1 (C1INT);INSERT intoT1VALUES(1);SELECT 'before Error', C1 fromT1 asT;
--The following is not executed SELECT 'Error', C1 fromNO_T1;--no_t1 table does not existSELECT 'After error'C1 fromT1 asT
For the above statement, the first 3 bars are executed. The error and subsequent statements have been revoked.
If the query contains an implicit data transformation, the canonical process adds a correct step in the query tree. The process also performs some syntax-based optimizations. Such as:
SELECT * from WHERE between - and Max
A syntax-based optimization translates the syntax of the query.
For most data definition language (DDL) statements, such as Create TABLE, create proc, and so on, after passing the algebra, the query is compiled directly for execution because the optimizer does not need to choose among a variety of processing strategies. For a special DDL statement, CREATE INDEX, the optimizer can determine an effective processing strategy based on an existing index on another table.
Therefore, the reference to create table is not seen in the execution plan, but you see a reference to the CREATE index. If a normalized query is a data manipulation language (DML) statement, the query processor tree is passed to the optimizer to determine the processing policy for the query.
third, optimize
Depending on the complexity of the query, including the referenced tables and the number of indexes available, queries contained in the query processor tree may be composed of multiple intimate methods. It may take more time to fully compare all the overhead of executing queries, and sometimes even finding the most optimized queries is not worth the candle. To avoid excessive optimization overhead, the optimizer uses different techniques, including:
- The useless plan matches;
- Multi-stage optimization;
- Parallel plan optimization;
1. Useless plan match
Sometimes there may be only one way to execute a query. For example, heap tables can only fetch data through table scans, and to avoid wasting time optimizing such queries, SQL Server maintains a list of useless schedules to choose from, and if the optimizer finds a plan that matches the query in the useless list, it generates a similar plan without any optimizations.
2. Multi-stage optimization
For complex queries, the number of alternative processing strategies that need to be analyzed can be large, and it can take a long time to evaluate each choice. As a result, the optimizer does not analyze all possible processing strategies, but instead divides them into several configurations, each with different indexing and connectivity techniques.
Index variants consider different index attributes, single-column indexes, composite indexes, index column order, index density, and so on. Similarly, the connection variants consider the different connection technologies available in SQL Server: Nested loop joins, merge joins, and hash matches.
The optimizer considers the statistics of the columns that are raised in the WHERE clause to evaluate the effectiveness of the index and connection policies. Based on the current statistics, it evaluates the overhead of the configuration in several optimization phases. The overhead includes many factors, including CPU, memory usage, and disk I/O required to execute the query. After each optimization phase, the optimizer evaluates the overhead of the processing policy. if the cost is sufficiently economical, the optimizer stops looping further through the optimization phase and exits the optimization process. Otherwise, continue to cycle through the optimization phase to determine a cost-effective processing strategy.
Sometimes queries may be too complex for the optimizer to iterate extensively during the optimization phase. When you refine a query, if you find that the processing policy is more expensive than the parallel open threshold, you use multiple CPUs to evaluate the cost of processing the query. Otherwise, the optimizer uses a serial plan.
- The size of the buffer plan;
- The CPU cycles used to compile the plan;
- The amount of memory used;
- Compile time;
The Optimize Horizontal property describes the type of processing that appears in the optimizer. In this example, full indicates that the optimizer is fully optimized. This is further prompted in the attribute "statement terminal cause" because "find a good enough plan". So, the optimizer spends 21ms to capture a plan that is considered good enough in this situation. You can also view the query plan hash value for the execution plan.
The second optimizer information turns out to be a dynamic management view sys.dm_exec_query_optimizer_info. This DMV is a collection of optimization events that does not show individual optimizations for a given query, but can track the optimization of rows. This cannot be directly used to adjust a single query, but if you intend to reduce the workload overhead at any time, tracking this information can help determine whether the query tuning has a positive impact, at least in terms of tuning time, and some of the returned data is used only inside SQL Server.
Execute the following query:
SELECT from Sys.dm_exec_query_optimizer_info
Run this query before and after a set of optimizations, and you can see the number of optimizations that have been completed and the types of changes.
3. Parallel Plan optimization
The optimizer uses a parallel plan to consider various factors when evaluating the cost of processing queries.
- The number of CPUs available for SQL Server;
- SQL Server version;
- Available memory;
- The type of query executed;
- The number of rows processed in the given stream;
- Number of active ice-law connections;
If only one CPU is available for SQL Server, the optimizer does not consider a parallel plan. The number of CPUs available for SQL Server can be displayed using the affinity mask setting configured by SQL Server. affinity mask value is a bitmap, one represents a CPU, and the rightmost position represents CPU0. For example, on a 8-way computer that only allows SQL Server to use CPU0-CPU3, execute the following statement:
use master exec sp_configure " show advanced option ", " 1 " reconfigure exec sp_configure " affinity Mask , 15 --bitmap: 00001111 reconfigure
This configuration takes effect immediately. Affinity mask is a special setting that is recommended to use only if it is not meaningful to deprive SQL Server control, such as having multiple instances of SQL Server running on the same computer and wanting them to be isolated from each other, to set up more than 32 processors, you must use only the SQL The affinity64 mask option is available on the Server64-bit version. You can also use the affinity mask I/o option to bind I/O to a specific processor set.
Even if multiple CPUs are available for SQL Server. The maximum number of CPUs that a parallel query can use is managed by the max degree of parallelism settings in SQL Server configuration. The default value is 0, which allows all CPUs (affinity mask settings available) to be used for parallel queries.
If you want to run a parallel query that uses no more than 2 CPUs in Cpu0-cpu3, execute the following statement:
Use Master EXEC ' Show Advanced Option ','1'RECONFIGUREEXEC'max degree of Parallelism',2 --set query to use up to 2 CPUs
RECONFIGURE
This modification takes effect immediately and does not require a restart. Max degree of parallelism Settings page can use MAXDOP query hints
Control at the query level:
SELECT * from WHERE Name=' Zhang San 'OPTION2)
Modifying the max degree of parallelism settings is best determined by the system requirements. To limit contention with the operating system, you typically set max degree of parallelism to 1 less than the number of server CPUs and set affinity mask to these CPUs.
Because parallel queries require more memory, the optimizer needs to determine the amount of available memory before choosing a parallel plan. The amount of memory required increases with parallel programs. If the parallel plan memory requirements for a given degree of parallelism are not met, SQL Server will automatically reduce the degree of parallelism or abandon the parallel plan entirely in the context of a given workload.
The best candidate for concurrent scheduling when querying with very high CPU overhead. such as a table with large joins, performs a large number of aggregation operations, and sorts large result sets. For simple queries that are typically found in transactional applications, the additional adjustments required to initialize, synchronize, and stop parallel plans outweigh the potential performance benefits.
The query is simple to determine by comparing the estimated execution time and cost thresholds. This overhead threshold is controlled by the cost threshold for parallelism settings configured by SQL Server. By default, this setting is 5, which means that if the execution time of a serial plan estimate exceeds 5 seconds, the optimizer considers using a parallel plan. For example, to modify the cost threshold to 6 seconds, execute the following statement:
Use Master EXEC ' Show advances option ','1'RECONFIGUREEXEC'costthreshold for Parallelism',6RECONFIGURE
This modification does not require a restart to take effect immediately. If only one CPU is available for SQL Server, this setting is ignored. The OLTP system is compromised because of the low parallelism threshold setting. It is generally advantageous to increase these values to 15-25 seconds.
DML operations Queries (INSERT, update, and delete) are serial queries. However, the select part of the INSERT statement and the WHERE statement of the update or DELETE statement can be executed in parallel. Actual data modifications are strictly applied to the database. Also, if the optimizer determines that there are too few rows affected, it does not introduce parallel operators.
Note that even when executed, SQL Server determines whether the current system workload and configuration information allow parallel query plans. If parallel query plans are allowed, SQL Server determines the number of out-of-the-box and distributes the execution of the query to those threads. When the query starts executing in parallel, it uses the same number of threads until it finishes. SQL Server re-examines the optimal number of threads the next time a parallel query is executed.
After the processing policy is finalized using a serial or parallel plan, the optimizer executes the plan after the query is generated. The execution plan includes a detailed processing strategy that the optimizer determines to execute the query. This includes steps such as data retrieval, result set joins, and result set sorting.
The resulting query plan is saved in the plan buffer for future use.
Build of execution plan