Invoke-sqmQueryStore Performance

Configures the Query Store, reads top-N queries, and detects issues (READ_ONLY, memory pressure, plan regression, forced plan failures, execution variance) across one or all user databases.

Execution Flow

START dbatools available? throw + ERROR NO Resolve SqlInstance / defaults No switch? → runQuery + runDiagnose = true OutputPath = Get-sqmDefaultOutputPath\QueryStore Get-DbaDatabase (filter target DBs) foreach $db in $targetDatabases Always: read sys.database_query_store_options if $runConfigure ShouldProcess Low ALTER DATABASE SET QUERY_STORE ON QS active? (READ_WRITE/READ_ONLY) add Issue + continue NO if $runQuery Invoke-DbaQuery: sys.query_store_* TOP N if $runDiagnose D1: READ_ONLY? → decode ReadOnlyReason D2: StoragePct ≥ StorageWarningPct? D3: PlanCount ≥ MaxPlansWarning → PlanInstability D4: force_failure_count > 0 → ForcedPlanFailure D5: variation_pct > 300 → HighVariance → Issues[], IssueCount Save CSV (TopQueries) + TXT (Issues) Return $allDbResults[] DONE

Synopsis

Comprehensive Query Store management for one, multiple, or all user databases. Supports three combinable operating modes: Configure (ALTER DATABASE SET QUERY_STORE), Query (top-N query analysis), and Diagnose (READ_ONLY detection, memory pressure, plan regression, forced plan failures, execution variance). Without explicit switches, Query + Diagnose are active (report mode).

Requires: dbatools, VIEW DATABASE STATE. Available from SQL Server 2016 (compatibility level ≥ 130).

Syntax

Invoke-sqmQueryStore
    [-SqlInstance <String>]
    [-SqlCredential <PSCredential>]
    [-Database <String[]>]
    [-All]
    [-Configure] [-Query] [-Diagnose]
    [-OperationMode <READ_WRITE|READ_ONLY|OFF>]
    [-FlushIntervalSeconds <Int>]
    [-IntervalLengthMinutes <Int>]
    [-MaxStorageSizeMB <Int>]
    [-QueryCaptureMode <ALL|AUTO|NONE>]
    [-SizeBasedCleanupMode <OFF|AUTO>]
    [-MaxPlansPerQuery <Int>]
    [-TopN <Int>] [-OrderBy <String>]
    [-LookbackHours <Int>]
    [-MinExecutionCount <Int>]
    [-StorageWarningPct <Int>]
    [-MaxPlansWarning <Int>]
    [-OutputPath <String>]
    [-EnableException]

Parameters

ParameterTypeDefaultDescription
-SqlInstanceString$env:COMPUTERNAMESQL Server instance to connect to.
-SqlCredentialPSCredentialCredential for the SQL connection.
-DatabaseString[]One or more databases. Ignored when -All is set.
-AllSwitchfalseProcess all accessible user databases.
-ConfigureSwitchfalseEnable and configure Query Store (ALTER DATABASE SET QUERY_STORE).
-QuerySwitchfalseRead top-N queries from the Query Store.
-DiagnoseSwitchfalseDetect issues and return them as Issue objects.
-OperationModeStringREAD_WRITEQuery Store mode: READ_WRITE, READ_ONLY, OFF.
-FlushIntervalSecondsInt900Frequency of flushing data to disk (60–86400 s).
-IntervalLengthMinutesInt60Length of one statistics interval in minutes.
-MaxStorageSizeMBInt1000Maximum Query Store size in MB (10–10240).
-QueryCaptureModeStringAUTOALL, AUTO, or NONE.
-SizeBasedCleanupModeStringAUTOOFF or AUTO — auto cleanup under storage pressure.
-MaxPlansPerQueryInt200Maximum execution plans stored per query.
-TopNInt25Number of top queries to return (1–1000).
-OrderByStringDurationSort column: Duration, CPU, LogicalReads, ExecutionCount, Memory.
-LookbackHoursInt24How many hours back to look (1–8760).
-MinExecutionCountInt5Minimum executions for a query to appear in results.
-StorageWarningPctInt80Storage fill percentage that triggers a Warning issue.
-MaxPlansWarningInt5Plan count per query that triggers a PlanInstability issue.
-OutputPathStringConfig\QueryStoreDirectory for CSV and TXT report files.
-EnableExceptionSwitchfalseThrow terminating exceptions instead of writing errors.

Return Value

Array of [PSCustomObject] — one entry per database:

PropertyTypeDescription
SqlInstanceStringTarget SQL Server instance.
DatabaseNameStringDatabase name.
QSOptionsDataRowCurrent Query Store options from sys.database_query_store_options.
ConfigureStatusString'Success' or 'Failed: …' — only populated when -Configure is used.
TopQueriesDataRow[]Top-N query records from the Query Store.
IssuesPSCustomObject[]Detected issues with Severity, Category, Description, Detail.
IssueCountIntTotal number of issues found.
ReportFileStringPath to the written TXT issues report, if any.

Examples

# Report mode: Query + Diagnose for all databases
Invoke-sqmQueryStore -All

# Configure and immediately query + diagnose
Invoke-sqmQueryStore -Database "SalesDB","CRM" -Configure -Query -Diagnose

# Top 50 queries by CPU consumption, last 48 hours
Invoke-sqmQueryStore -Database "SalesDB" -Query -TopN 50 -OrderBy CPU -LookbackHours 48

# Diagnostics with lower storage threshold and custom report path
Invoke-sqmQueryStore -All -Diagnose -StorageWarningPct 70 -OutputPath "D:\Reports\QS"

Diagnose Issue Categories

CategorySeverityCondition
QSDisabledCriticalQuery Store is OFF — cannot run Query or Diagnose.
ReadOnlyCriticalActualState = READ_ONLY. Decodes ReadOnlyReason code (1=size, 2=compat, 4=recovery, 8=ALTER, 65=combined).
StoragePressureWarning/CriticalStoragePct ≥ StorageWarningPct (Critical at ≥ 95%).
PlanInstabilityWarning/CriticalQuery has ≥ MaxPlansWarning distinct plans. Critical if regression > 200%.
ForcedPlanFailureCriticalis_forced_plan=1 AND force_failure_count > 0.
HighVarianceWarningExecution time variation > 300% over lookback period.

Notes

Requires dbatools and VIEW DATABASE STATE permission on each target database. Query Store is available from SQL Server 2016 (compatibility level ≥ 130).
If no operating switch (-Configure / -Query / -Diagnose) is specified, the function runs in report mode: both -Query and -Diagnose are activated automatically.