dataiotech Labs
dbaguidedbaguideDBAdataxtoolsdataopsphere
Scripts Library/sqlserver/#60
Script #60
sqlserver
Performanceread-onlyMin Version: 2016

Find Parameter Sniffing Candidates with Query Store

Finds queries with multiple plans and large duration variance. Diagnoses plan regressions and parameter sniffing problems.

#parameter-sniffing#query-store#plan-regression
sqlserver · sql
SELECT TOP 20 q.query_id,
       COUNT(DISTINCT p.plan_id) AS plan_count,
       MIN(rs.avg_duration) / 1000 AS min_avg_ms,
       MAX(rs.avg_duration) / 1000 AS max_avg_ms,
       MAX(rs.avg_duration) / NULLIF(MIN(rs.avg_duration), 0) AS ratio,
       LEFT(qt.query_sql_text, 150) AS query_text
FROM sys.query_store_query q
JOIN sys.query_store_query_text qt ON qt.query_text_id = q.query_text_id
JOIN sys.query_store_plan p ON p.query_id = q.query_id
JOIN sys.query_store_runtime_stats rs ON rs.plan_id = p.plan_id
GROUP BY q.query_id, qt.query_sql_text
HAVING COUNT(DISTINCT p.plan_id) > 1
ORDER BY ratio DESC;
Operational Notes & Remediation Guidance

Query Store helps identify queries with high plan variance caused by parameter sniffing; consider `OPTIMIZE FOR` hints.

Production Safety & Execution Standards
  • This script is designed for read-only diagnostics; it does not alter schema or modify data directly.
  • Prior to executing on production systems under high load, verify the target database version (Min. Version: 2016).
  • Exercise caution with mutating actions (e.g., terminating sessions or dropping indexes) referenced in the notes section.