Thor Logo dbatools

Get-DbaQueryExecutionTime

View Source
Brandon Abshire, netnerds.net
Windows, Linux, macOS

Synopsis

Retrieves stored procedures and SQL statements with the highest CPU execution times from SQL Server instances.

Description

Analyzes SQL Server’s query execution statistics to identify performance bottlenecks by examining CPU worker time data from dynamic management views. This function queries sys.dm_exec_procedure_stats for stored procedures and sys.dm_exec_query_stats for ad hoc statements, returning detailed execution metrics including average execution time, total executions, and maximum execution time.

Use this when troubleshooting performance issues, identifying resource-intensive queries during peak hours, or conducting routine performance audits. The results help pinpoint which stored procedures or SQL statements are consuming the most CPU resources across your databases, so you don’t have to manually query DMVs or run expensive profiler traces.

By default, returns the top 100 results per database for queries executed at least 100 times with an average execution time of 500ms or higher. Results include the full SQL text for ad hoc statements and procedure names for stored procedures, along with execution statistics and timing data.

Syntax

Get-DbaQueryExecutionTime -SqlInstance <DbaInstanceParameter[]>
    [-SqlCredential <PSCredential>]
    [-Database <Object[]>]
    [-ExcludeDatabase <Object[]>]
    [-MaxResultsPerDb <Int32>]
    [-MinExecs <Int32>]
    [[-MinExecMs] <Int32>]
    [[-ExcludeSystem]]
    [-EnableException]
    [<CommonParameters>]

 

Examples

 

Example: 1
PS C:\> Get-DbaQueryExecutionTime -SqlInstance sql2008, sqlserver2012

Return the top 100 slowest stored procedures or statements for servers sql2008 and sqlserver2012.

Example: 2
PS C:\> Get-DbaQueryExecutionTime -SqlInstance sql2008 -Database TestDB

Return the top 100 slowest stored procedures or statements on server sql2008 for only the TestDB database.

Example: 3
PS C:\> Get-DbaQueryExecutionTime -SqlInstance sql2008 -Database TestDB -MaxResultsPerDb 100 -MinExecs 200 -MinExecMs 1000

Return the top 100 slowest stored procedures or statements on server sql2008 for only the TestDB database, limiting results to queries with more than 200 total executions and an execution time over
1000ms or higher.

Required Parameters

-SqlInstance

The target SQL Server instance or instances.

PropertyValue
Alias
RequiredTrue
Pipelinetrue (ByValue)
Default Value

Optional Parameters

-SqlCredential

Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).
Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.
For MFA support, please use Connect-DbaInstance.

PropertyValue
Alias
RequiredFalse
Pipelinefalse
Default Value
-Database

Specifies which databases to analyze for query execution statistics. Accepts wildcards for pattern matching.
Use this when troubleshooting performance issues in specific databases instead of scanning all databases on the instance.
Helpful for focusing on production databases or isolating performance analysis to databases experiencing issues.

PropertyValue
Alias
RequiredFalse
Pipelinefalse
Default Value
-ExcludeDatabase

Specifies databases to skip during the execution time analysis. Accepts wildcards for pattern matching.
Use this to avoid processing databases that are known to be performing well or contain only static reference data.
Common use case is excluding development or staging databases when analyzing production performance.

PropertyValue
Alias
RequiredFalse
Pipelinefalse
Default Value
-MaxResultsPerDb

Limits the number of top execution time results returned per database. Defaults to 100 results.
Specify a lower number for quick performance overviews or higher numbers for comprehensive analysis.
Large values may impact query performance on busy systems with extensive plan cache data.

PropertyValue
Alias
RequiredFalse
Pipelinefalse
Default Value100
-MinExecs

Filters results to queries that have executed at least this many times. Defaults to 100 executions.
Use this to focus on frequently-run queries that have consistent performance patterns rather than one-time queries.
Higher values help identify truly problematic queries that impact system performance regularly.

PropertyValue
Alias
RequiredFalse
Pipelinefalse
Default Value100
-MinExecMs

Filters results to queries with an average execution time of at least this many milliseconds. Defaults to 500ms.
Use this to focus on genuinely slow queries rather than fast queries that happen to consume CPU cycles.
Lowering this value shows more queries but may include acceptable performance levels.

PropertyValue
Alias
RequiredFalse
Pipelinefalse
Default Value500
-ExcludeSystem

Skips analysis of system databases (master, model, msdb, tempdb).
Use this when focusing performance analysis on user databases only, since system database queries are typically administrative.
System database performance issues are usually infrastructure-related rather than application code problems.

PropertyValue
AliasExcludeSystemDatabases
RequiredFalse
Pipelinefalse
Default ValueFalse
-EnableException

By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
This avoids overwhelming you with “sea of red” exceptions, but is inconvenient because it basically disables advanced scripting.
Using this switch turns this “nice by default” feature off and enables you to catch exceptions with your own try/catch.

PropertyValue
Alias
RequiredFalse
Pipelinefalse
Default ValueFalse

Outputs

PSCustomObject

Returns one object per stored procedure or SQL statement matching the specified execution time filters. Results are limited to the top N results per database based on average CPU worker time (highest first), where N is controlled by -MaxResultsPerDb (default 100).

Default display properties (via Select-DefaultView):

  • ComputerName: The name of the computer hosting the SQL Server instance
  • InstanceName: The SQL Server instance name
  • SqlInstance: The full SQL Server instance name (computer\instance format)
  • Database: The name of the database containing the query
  • ProcName: The procedure or object name; empty string for ad hoc statements
  • ObjectID: The object ID from sys.dm_exec_procedure_stats or sys.dm_exec_query_stats
  • TypeDesc: The type description - “PROCEDURE” for stored procedures or “STATEMENT” for ad hoc queries
  • Executions: The execution_count - total number of times the query has been executed
  • AvgExecMs: Average execution time in milliseconds (total_worker_time / execution_count / 1000)
  • MaxExecMs: Maximum execution time in milliseconds (max_worker_time / 1000)
  • CachedTime: DateTime when the query plan was cached (1901-01-01 for ad hoc statements)
  • LastExecTime: DateTime when the query last executed
  • TotalWorkerTimeMs: Total CPU worker time in milliseconds across all executions
  • TotalElapsedTimeMs: Total elapsed time in milliseconds across all executions
  • SQLText: Truncated SQL text (first 50 characters for ad hoc statements, procedure name for stored procedures)

*Additional properties (available with Select-Object ):

  • FullStatementText: Complete SQL statement text (full T-SQL for ad hoc statements, procedure name for stored procedures)