When you execute the stored procedure with the Show Execution Plan option enabled, SSMS displays only the execution plans for the path or statements that are actually executed, as shown
Trang 1Stream Aggregate
You most often see the Stream Aggregate operation when you are aggregating a single input,
such as a DISTINCT clause or a SUM, COUNT, MAX, MIN, or AVG operator The output of this
oper-ator may be referenced by later operoper-ators in the query, returned to the client, or both
Because the Stream Aggregate operator requires input ordered by the columns within its
groups, a Sort operator often precedes the Stream Aggregate operator unless the data is
already sorted due to a prior Sort operator or due to an ordered index seek or scan
Table Delete , Table Insert , Table Scan , and Table Update
You see the Table Delete, Table Insert, Table Scan, and Table Update operators when the
indicated operation is being performed against that table as a whole The presence of these
operators does not always mean a problem exists, although a table scan can be an
indica-tor that you might need some indexes to support the query A table scan may be
performed on small tables even if appropriate indexes exist, especially when the table is
only a single page or two in size
Table-valued Function
The Table-valued Function operator is displayed for queries with calls to table-valued
func-tions The Table-valued Function operator evaluates the table-valued function, and the
resulting rows are stored in the tempdb database When the parent operators request the
rows, the Table-valued Function operator returns the rows from tempdb
Top
The Top operator indicates a limit that is set, either by number of rows or a percentage, on
the number of results to be returned from the input The ToolTip may also contain a list
of the columns being checked for ties if the WITH TIES option has been specified
Parallelism Operators
The Parallelism operators indicate that parallel query processing is being performed The
associated logical operator displayed is one of the Distribute Streams, Gather Streams, or
Repartition Streams logical operators
Distribute Streams The Distribute Streams operator takes a single input stream of
records and produces multiple output streams Each record from the input stream
appears in one of the output streams Hashing is typically used to decide to which output
stream a particular input record belongs
Gather Streams The Gather Streams operator consumes several input streams and
produces a single output stream of records by combining the input streams If the output is
ordered, the ToolTip will contain an Order By item indicating the columns being ordered
Trang 21315 Query Analysis in SSMS
NOTE
Parallel query processing strategies are covered in more detail in Chapter 35
Analyzing Stored Procedures
When displaying the estimated execution plan for a stored procedure, you see multiple
statement operators as inputs to the Stored Procedure operator, especially if you have any
conditional branching in the stored procedure One operator exists for each statement
defined in the stored procedure When conditional branching occurs in the stored
proce-dure, SQL Server does not know at query optimization time which statements in the
stored procedure will actually be executed, so it has to estimate a query plan for each
indi-vidual statement An example is shown in Figure 36.7
When you execute the stored procedure with the Show Execution Plan option enabled,
SSMS displays only the execution plans for the path or statements that are actually
executed, as shown in Figure 36.8
FIGURE 36.7 Estimated execution plan for a stored procedure
Trang 3In addition, because stored procedures can become quite complex, with multiple SQL
statements, seeing the graphical execution plan in the SSMS Execution Plan window can
be difficult You might find it easier to break up the stored procedure into smaller batches
or individual queries and analyze it a bit at a time
Saving and Viewing Graphical Execution Plans
SQL Server Management Studio 2008 enables you to save an execution plan as an XML
file To save a graphical execution plan in SSMS, you right-click anywhere on the graphical
execution plan and choose Save Execution Plan As to bring up the Save As dialog
(alterna-tively, you can choose the Save Execution Plan As option from the File menu)
When you save the execution plan to a file, the graphical execution plan is saved as an
XML, file with the sqlplan file extension To view a saved execution plan, click on the
File menu; select Open and then File In the Open File dialog, select Execution Plan files
in the Files of Type drop-down to limit the files displayed to just Execution Plan Files (see
FIGURE 36.8 Actual execution plan used for a stored procedure
Trang 41317 Query Analysis in SSMS
tion plan was originally generated, you can mouse over the operators and display the
detailed information contained in the ToolTips
Displaying Execution Plan XML
In addition to viewing the graphical execution plan in SSMS, you can also display the
XML generated by the Query Optimizer that is used to create the graphical execution
plan Right-click on the execution plan and select the Show Execution Plan XML option
(see Figure 36.10)
Selecting this option opens a new XML editor window with the SHOWPLAN_XML output
generated by the query optimizer
Missing Index Hints
One new feature in SQL Server Management Studio 2008 is Missing Index Hints when
displaying the execution plan of a query You can use the Missing Index Hints feature to
help identify columns on which adding an index might help the query execute faster and
more efficiently Missing Index Hints is a lightweight, server-side, always-on feature using
dynamic management objects and execution plans to provide information about missing
indexes that could enhance query performance
FIGURE 36.9 Loading an execution plan into SSMS
Trang 5FIGURE 36.10 Generating execution plan XML in SSMS
NOTE
The Missing Index Hints feature is separate from the Database Engine Tuning Advisor
available in SQL Server 2008 The Database Engine Tuning Advisor is a more
compre-hensive tool that assesses the physical database design and recommends new
physi-cal design structures for performance improvement In addition to index
recommendations, it also considers whether indexed views or partitioning could be
used to improve query performance
When the query optimizer generates an execution plan, it analyzes what are the best
avail-able indexes for a the specified search and join conditions If a useful index is not found,
the query optimizer generates a suboptimal query plan but still stores information about
the missing indexes The Missing Index Hints feature enables you to view information
about these indexes so you can decide whether they should be implemented
If any missing indexes are identified by the Query Optimizer, the Execution Plan tab in
SSMS displays information related to all the missing indexes If you put the mouse pointer
over the missing index text, it displays a ToolTip showing the T-SQL code required to
create the suggested missing index as suggested, as shown in Figure 36.11
In addition to displaying a ToolTip with the T-SQL code, you can also generate the SQL
Trang 61319 Query Analysis in SSMS
FIGURE 36.11 Displaying missing indexes in SSMS
FIGURE 36.12 Generating T-SQL code to create a missing index
Trang 7LISTING 36.1 SQL Generated by SSMS Missing Index Hints Feature
/*
Missing Index Details from multi_query.sqlplan
The Query Processor estimates that implementing the following index could improve
the query cost by 87.4584%
*/
/*
USE [bigpubs2008]
GO
CREATE NONCLUSTERED INDEX [<Name of Missing Index, sysname,>]
ON [dbo].[sales] ([qty])
INCLUDE ([stor_id])
GO
*/
If you examine the SQL generated by SSMS, notice that it displays the estimated associated
cost benefit expected by adding the recommended index Also note that the script does not
include an index name You need to specify an index name based on your naming standards
NOTE
If you decide to create a recommended index, be sure to review the subsequent query
plan to determine if the query is using the index and that it provides the expected
per-formance benefit
Missing Index Dynamic Management Objects
The Missing Index Hints feature in SSMS draws information regarding missing indexes
from a set of new dynamic management objects introduced in SQL Server 2008:
sys.dm_db_missing_index_group_stats—Returns summary information
about missing index groups, such as the performance improvements that could be
gained by implementing a specific group of missing indexes
sys.dm_db_missing_index_groups—Returns information about a specific group
of missing indexes, such as the group identifier and the identifiers of all missing
indexes contained in that group
sys.dm_db_missing_index_columns—Returns detailed information about a missing
index; for example, it returns the name and identifier of the table where the index is
missing, and the columns and column types that should make up the missing index
sys.dm_db_missing_index_details—Returns information about the database
Trang 81321 Query Analysis in SSMS
come in handy After running a typical workload on SQL Server, you can retrieve
informa-tion about missing indexes by querying the dynamic management funcinforma-tions directly You
can use the information returned by these dynamic management objects in scripts and
use the information to generate CREATE INDEX statements to create the missing indexes
Listing 36.2 provides a sample query that displays the missing index information for a
query on the sales table that was run between 10:30 and 10:40 p.m on February 21,
2010
LISTING 36.2 Querying the Missing Index Dynamic Management Objects
SELECT
mig.index_group_handle as handle,
convert(varchar(30), statement) AS table_name,
convert(varchar(12), column_name) AS Column_name,
convert(varchar(10), column_usage) as ColumnUsage,
avg_user_impact as avg_impact
FROM sys.dm_db_missing_index_details AS mid
CROSS APPLY sys.dm_db_missing_index_columns (mid.index_handle)
INNER JOIN sys.dm_db_missing_index_groups AS mig
ON mig.index_handle = mid.index_handle
inner join sys.dm_db_missing_index_group_stats AS migs
ON migs.group_handle = mig.index_group_handle
where mid.object_id = object_id(‘sales’)
and last_user_seek between ‘2010-02-21 22:30’ and ‘2010-02-21 22:40’
ORDER BY mig.index_group_handle, mig.index_handle, column_id;
GO
handle table_name Column_name ColumnUsage avg_impact
- -
-2 [bigpubs -2008].[dbo].[sales] stor_id INCLUDE 87.46
2 [bigpubs2008].[dbo].[sales] qty INEQUALITY 87.46
If you view the output of this query, you see that the optimizer is recommending an index
on the qty column to support an inequality operator It is also recommended that the
stor_id column be specified as an included column in the index This index is estimated
to improve performance by 87.46% When you use this information, the CREATE INDEX
statement for the recommended index would be the following:
CREATE INDEX qty_idx on [bigpubs2008].[dbo].[sales] (qty) INCLUDE (stor_id)
Missing Index Hints Features Limitations
The Missing Index Hints feature provides some helpful information for identifying
poten-tially missing indexes in your database, but it does have a few limitations:
Trang 9It is not intended to fine-tune the existing indexes, only to recommend additional
indexes when no useful index is found that can be used to satisfy a search or join
condition
It does not specify the order for columns to be specified in the index
For queries involving only inequality predicates, the cost information returned is less
accurate than for equality operators
It only recommends adding included columns to indexes for some queries instead of
creating composite indexes You need to determine whether the included columns
should be specified as additional index key columns instead
It returns only raw information about columns on which indexes might be missing
It may return different costs for the same missing index group for different executions
It does not suggest filtered indexes
The dynamic management objects can store information from a maximum of 500
missing indexes
It is unable to provide recommendations for clustered indexes, indexed views, or
table partitioning (Use the Database Engine Tuning Advisor instead for these
recommendations.)
After the SQL Server is restarted, all the information related to missing indexes is
lost To keep the information for later use, the DBA needs to back up all the data
available within all the missing index dynamic management objects prior to
restart-ing SQL Server
NOTE
Although the Missing Index Hints feature is helpful for identifying indexes that may be
useful for you to define, it’s not a substitute for a well-thought-out index design For
more information on index design, see Chapter 34, “Data Structures, Indexes, and
Performance.”
SSMS Client Statistics
You can use SSMS to get some additional information related to the client-side
perfor-mance of the query by toggling the Include Client Statistics option in the Query menu
When turned on, the Client Statistics tab is added to the Results panel This tab displays
useful performance statistics in a tabular format that is related to how much work the
Trang 101323 SSMS Client Statistics
average statistics across all executions Figure 36.13 shows an example of the client
statis-tics displayed after three separate query executions
The first line in the Client Statistics tab displays the actual time the query was executed
The Time Statistics values are specified in number of milliseconds Some of the most
useful pieces of information include the number of rows returned by SELECT statements,
total client processing time, total execution time, and number of bytes sent and received
across the network
The Average column contains the cumulative average since the Include Client Statistics
option was enabled Turning the option off and back on clears out all the historical
statis-tics and resets the averages Alternatively, you can also reset the client statisstatis-tics by
select-ing the Reset Client Statistics option from the Query menu
One of the most helpful features of the client statistics is the arrow indicators provided for
the different executions, which makes it easy to identify which values increased,
decreased, or stayed this same This feature makes it easy to compare the runtime statistics
between different queries or different executions of the same query
FIGURE 36.13 SSMS client statistics