SQL Server Locking and Blocking Analysis

AI SQL Tuner Studio showing a completed Locking and Blocking Analysis of a SQL Server 2025 database: executive summary naming session 88 as the lead blocker, with 5 blocked sessions, a 29,106 ms longest wait and 137,184 ms cumulative wait

Updated

Find the lead blocker and the root cause of SQL Server blocking in minutes. The Locking and Blocking Analysis goal in AI SQL Tuner Studio takes a snapshot of the current concurrency state of a user database: live blocking chains, locks, open transactions, blocker plans, deadlock history and isolation settings. It then asks the AI for a blocking tree, a root-cause classification and prioritized, evidence-cited fixes with confidence levels, rollback plans and ready-to-run scripts. The screenshot above shows one in Studio, run with GPT-5.6 Luna against live blocking on SQL Server 2025 (full size).

Watch: find the lead blocker in two minutes

This video explains what locking and blocking are, shows what Studio collects, and runs the analysis against live blocking: a billing job whose update escalated to a lock on the whole Orders table, with five sessions waiting behind it. After the report’s scripts were applied, the same workload had zero blocked sessions.

SQL Server Locking and Blocking: Find the Lead Blocker in Minutes (2:10)

Table of contents

What is the Locking and Blocking Analysis goal?

It is one of six tuning goals in AI SQL Tuner Studio. It answers the question “why is this database blocking right now, and what should I change first?” for SQL Server, Azure SQL Database, Azure SQL Managed Instance, SQL database in Microsoft Fabric and Amazon RDS for SQL Server.

Instead of switching between sp_who2, blocked process reports, the system_health Extended Events session, Query Store and DMV queries, you point the goal at a user database and get one HTML report. It correlates ten evidence sections, classifies the root cause and lists prioritized fixes, with the scripts to apply them.

Blocking is one finding among many on a busy server. For a broader review of backups, integrity, configuration and security, run a SQL Server health check as well.

How it works

  1. Connect to a user database. The goal requires one, and both the UI and core validation reject master, tempdb, model and msdb.
  2. Review the run plan. Before anything is sent, Studio shows the connection, the AI model and reasoning effort, and every collector that will run.
  3. Collect. Ten read-only collectors query DMVs, catalog views, Query Store and the system_health Extended Events session. Large sections are summarized: the lock inventory is grouped, deadlock graphs and blocker plans are condensed to the facts the analysis needs.
  4. Analyze. The snapshot is sent to the AI with a structured prompt for root-cause classification, evidence correlation across sections and per-fix confidence.
  5. Report. A prioritized HTML report comes back, typically in about a minute: executive summary, blocking tree, root-cause classification, the statements involved, prioritized fixes and a Scripts section you can export as a .sql file.

The ten evidence sections

Each section is collected with read-only queries and skips features that are unavailable. When something like Query Store or the system_health session is off or unreadable, the report says so and explains how to enable it, instead of failing.

# Section Impact Source What it surfaces
1 Active Blocking Chains High sys.dm_os_waiting_tasks, sys.dm_exec_requests, sys.dm_exec_sessions, sys.dm_exec_sql_text The lead blocker to waiter tree, with statement-level SQL, batch context, wait type, wait resource, wait duration, isolation level and lock timeout for each session. Waits on [COMPILE] resources show sessions queued behind another session’s compile.
2 Lock Inventory High sys.dm_tran_locks, sys.partitions, sys.indexes Held and requested locks for the target database plus tempdb, grouped by resource type, object, index, mode, status, session and login, with a lock count and a short SQL snippet. Waiting locks are listed first.
3 Long-Running Transactions High sys.dm_tran_active_transactions, sys.dm_tran_session_transactions, session and request DMVs Open read and write transactions ordered by duration, with session, login and current SQL text.
4 Index Usage Statistics High sys.dm_db_index_usage_stats, sys.indexes, sys.objects, sys.dm_db_partition_stats The top 50 indexes by seeks, scans and lookups, with update counts, index size and table row count: hotspot indexes and high-scan, low-seek patterns that widen lock coverage.
5 Missing Index Candidates High sys.dm_db_missing_index_details, sys.dm_db_missing_index_groups, sys.dm_db_missing_index_group_stats The top 20 candidates by estimated impact: scan-causing gaps that directly increase how many rows a statement locks.
6 Blocker Query Plans High sys.dm_exec_requests, sys.dm_exec_sql_text, sys.dm_exec_text_query_plan For every blocking or waiting session, the running statement and a summary of its own cached plan: each table and index it reads or writes, with estimated rows, rows read and share of the statement cost, plus residual predicates that force scans, plan warnings and missing indexes.
7 Deadlock History High system_health Extended Events session Up to 10 recent deadlocks, each summarized as its processes (victim, isolation level, lock waited for, code and statement) and its locked resources with owners and waiters. A capture status line tells the AI whether capture is working, stopped, denied or unavailable on the platform.
8 Query Store Top Queries Medium sys.query_store_query, sys.query_store_plan, sys.query_store_runtime_stats The top 20 queries by total CPU time. On SQL Server 2022 and later, variants of adaptive plans are listed under their parent query. When Query Store is off, the report includes the ALTER DATABASE statement to enable it.
9 Database Settings Medium sys.databases, sys.database_scoped_configurations, sys.tables RCSI, snapshot isolation, synchronous and asynchronous auto-update statistics, accelerated database recovery (ADR), optimized locking, OPTIMIZED_SP_EXECUTESQL, ASYNC_STATS_UPDATE_WAIT_AT_LOW_PRIORITY, version store health and each table’s lock escalation setting (TABLE, AUTO or DISABLE).
10 TempDB Contention Medium sys.dm_os_wait_stats, sys.dm_db_file_space_usage, sys.dm_exec_query_stats PAGELATCH, PAGEIOLATCH and LATCH waits, version store and free space, internal and user objects, and the top 10 spilling queries.

What the AI produces

The AI receives all ten sections and returns a prioritized HTML report with these parts:

  1. Executive summary and impact: whether blocking is active, the lead blocker, the number of blocked sessions, and the longest and cumulative waits.
  2. Blocking tree: the lead blocker, its immediate waiters and the sessions waiting on them, drawn as a diagram.
  3. Root-cause classification: each category assessed with evidence lines from the collected sections. The categories are long-running transaction, open transaction with no activity, hotspot table or index, lock escalation, SERIALIZABLE or REPEATABLE READ misuse, implicit transactions, parameter sniffing causing large scans, missing index causing lock amplification, RBAR or cursor patterns, and TempDB contention masquerading as blocking.
  4. Important statements: the blocker and waiter SQL that causes or amplifies the blocking.
  5. Prioritized fixes: each with its rationale and evidence, risk, rollback plan, confidence level (High, Medium or Low) and the waits or lock conflicts it removes. Percentages appear only as labelled estimates with their basis.
  6. Code and query changes: when the SQL shows wide scans, overly broad updates or deletes, poor batching or long transaction scope, the AI gives before-and-after T-SQL, and puts the complete revised statement in the Scripts section.
  7. Settings guidance: RCSI, snapshot isolation and, on SQL Server 2025, ADR followed by optimized locking, recommended only when the evidence shows the blocking they remove and never when they are already on.
  8. Long-term mitigations and enablement advisories: patterns from deadlock history or Query Store, and how to turn on Query Store or deadlock capture when they are missing.

Index recommendations point you to the Index Tuning goal for the named table, which checks a new index against the table’s existing indexes and workload.

Example: live blocking on SQL Server 2025

For the video above, a test database reproduced a common pattern. A billing job opened a transaction and ran a procedure that updated 37,093 Orders rows, so SQL Server escalated its row locks to an exclusive lock on the whole table. Five sessions from three applications queued behind it, two of them two levels deep. The analysis ran while the chain was live and returned its report 54 seconds after the snapshot was sent.

SQL Server blocking tree from an AI SQL Tuner Studio report: lead blocker session 88 holds an object-level X lock in a 33-second transaction running dbo.usp_ApplyLateFees, with sessions 89, 109 and 110 waiting on it and sessions 90 and 111 waiting on session 89
The blocking tree from that report: session 88 is the lead blocker, and session 89 is both a waiter and a blocker.

The report classified the root cause as a long-running transaction made worse by lock escalation, and it recommended a covering index for the balance query that scanned Orders, RCSI, ADR followed by optimized locking, and asynchronous statistics updates. After those scripts were applied and the same workload was replayed, with the billing transaction still open, blocked sessions went from 5 to 0. The billing job no longer held a table-level X lock.

Interpretation guide

Section What to look for
Active Blocking Chains The lead blocker’s session ID, wait type and total waiter count. A chain of three or more waiters signals a critical blocker. A wait resource ending in [COMPILE] means sessions are waiting for another session to finish compiling the same batch or module.
Lock Inventory S or X locks at OBJECT or HOBT level indicate lock escalation; intent locks such as IX do not. Many KEY or PAGE locks on one table indicate hotspot access.
Long-Running Transactions A transaction open for more than about 30 seconds without an active request is often an orphaned or idle-open transaction.
Index Usage High user_scans with low user_seeks on a large table means queries scan rather than seek, holding more locks for longer.
Missing Indexes High-impact candidates suggest full or range scans where a seek would do. The right index turns scans into seeks and sharply reduces lock coverage.
Blocker Plans Clustered index or table scans whose rows read far exceed their estimated rows, especially with a high share of the statement cost or a residual predicate. These operators touch, and lock, every row they read.
Deadlock History Recurring deadlocks on the same tables or indexes suggest a consistent access-order problem or a missing covering index. For a full deadlock rewrite, use the Fix Deadlocks goal.
Query Store Top Queries Frequent high-CPU queries can hold locks for long periods. Several plans for the same query can mean parameter sniffing is causing unpredictable scans.
Database Settings With RCSI OFF under READ COMMITTED, enabling RCSI removes most reader-writer blocking. On SQL Server 2025 with optimized locking OFF, enabling ADR and then optimized locking makes lock escalation far less likely and, with RCSI on, stops writers on different rows from blocking each other. With optimized locking ON, remaining blocking usually comes from REPEATABLE READ or SERIALIZABLE, lock hints, schema locks or long-running writers.
TempDB Contention High PAGELATCH_UP or PAGELATCH_EX waits with a large version store point to row-versioning pressure in TempDB. Spilling queries should be tuned so they get adequate memory grants.

Enable full historical capture

Enable Query Store

Query Store is enabled per database. Run the following while connected to the target database:

ALTER DATABASE [YourDatabase] SET QUERY_STORE = ON;
ALTER DATABASE [YourDatabase] SET QUERY_STORE (
    OPERATION_MODE = READ_WRITE,
    MAX_STORAGE_SIZE_MB = 1024,
    INTERVAL_LENGTH_MINUTES = 60,
    QUERY_CAPTURE_MODE = AUTO
);

With Query Store enabled, the report can correlate recurring high-CPU queries with blocking.

Verify the system_health Extended Events session

The system_health session is on by default in SQL Server. sys.dm_xe_sessions lists only running sessions, so it is running if this query returns a row:

SELECT name, create_time
FROM sys.dm_xe_sessions
WHERE name = 'system_health';

If it returns no row, start it:

ALTER EVENT SESSION [system_health] ON SERVER STATE = START;

system_health keeps only a short rolling history. If deadlocks recur, a dedicated Extended Events session with the sqlserver.xml_deadlock_report event and an event_file target keeps them longer. On Azure SQL Database and SQL database in Microsoft Fabric, system_health cannot be read, so deadlocks are captured with a database-scoped event session for sqlserver.database_xml_deadlock_report. The report recommends this when it applies.

Sample report

This real report was generated against the WideWorldImporters sample database on SQL Server 2022 Developer Edition. It finds a session holding an exclusive key lock on Application.StateProvinces in an idle open transaction, with a reader that had waited for more than 31 hours. It ties the deadlock history to opposite-order updates of the same tables, and ranks fixes from ending the open transaction to a supporting index on Application.Cities, each with its confidence level and scripts.

View the full sample Locking and Blocking Analysis report →

More sample reports for every goal are at reports.aisqltuner.com.

Supported platforms

  • SQL Server 2016 and later, on-premises or in a VM, in every edition: Developer, Express, Standard and Enterprise. Deadlock history is read from the system_health file target. Optimized locking is checked on SQL Server 2025.
  • Azure SQL Managed Instance and Amazon RDS for SQL Server. Deadlock history is read from both the system_health files and its ring buffer, and a deadlock found in both is reported once.
  • Azure SQL Database and SQL database in Microsoft Fabric. system_health cannot be read there, so the report recommends a database-scoped event session for deadlock capture instead of showing deadlock history.
  • On Azure SQL Database, Managed Instance and Fabric, the platform manages optimized locking, so the report mentions it but gives no script for it.

Safety and permissions

  • The goal requires a user database. The UI and core validation reject master, tempdb, model and msdb.
  • All ten collectors are read-only. They query DMVs and catalog views and never read or change your tables’ data, so they are safe to run during an active blocking incident.
  • The run plan lists every collector before anything is sent, and the lock inventory, deadlock graphs and blocker plans are summarized to keep the request small.
  • A least-privileged login is enough; the scripts on that page grant the server and database state permissions the collectors need. If deadlock history cannot be read, the report names the missing permission (VIEW SERVER STATE, or VIEW SERVER PERFORMANCE STATE on SQL Server 2022 and later) instead of claiming capture is off.
  • If Query Store or deadlock capture is unavailable, the report includes an advisory instead of failing.

Frequently asked questions

What is SQL Server locking and blocking analysis?

It is the process of finding which sessions hold locks, which sessions wait on them, what statements they run, and which root cause produces the blocking: a long-running or idle-open transaction, lock escalation, a missing index, a hotspot, the isolation level or TempDB pressure. AI SQL Tuner Studio automates that correlation across blocking chains, lock inventory, blocker plans, Query Store, deadlock history, database settings and TempDB.

How long does an analysis take?

Typically about a minute from the time the snapshot is sent. In the video above, the report came back in 54 seconds.

Does Locking and Blocking Analysis work on Azure SQL Database and Managed Instance?

Yes. On Azure SQL Managed Instance, deadlock history is read from the system_health files and ring buffer. On Azure SQL Database and SQL database in Microsoft Fabric, system_health cannot be read, so the report recommends a database-scoped event session for deadlock capture. Sections that depend on a feature the platform lacks are skipped with a note rather than failing the run.

Will it recommend RCSI or optimized locking?

Only when the evidence supports it. The report recommends RCSI when readers wait on writers under READ COMMITTED and RCSI is off. On SQL Server 2025 it recommends enabling ADR and then optimized locking when it sees lock escalation or writers blocking each other, with the scripts in order, the maintenance-window requirement and the rollback steps. It never recommends a setting that is already on.

How is this different from Fix Deadlocks?

Locking and Blocking Analysis looks at blocking happening now in one database, and uses deadlock history as supporting evidence. Fix Deadlocks reads the deadlock graphs across the server, with the code involved, and returns rewritten procedures that prevent them.

Can I run this against master or tempdb?

No. The goal requires a user database. Both the UI and core validation reject master, tempdb, model and msdb.

Will collection itself cause blocking?

No. All ten collectors run read-only DMV and catalog queries that never touch your tables’ data, so they are safe to run during an active blocking incident.

Does the AI provide rewrite examples for the offending SQL?

Yes, when the blocker or waiter SQL shows scans, broad updates or deletes, poor batching or long transaction scope. The AI gives before-and-after T-SQL and puts the complete revised statement in the Scripts section. When the statement sits inside a procedure whose full definition was not collected, it gives the revised statement and names the module, rather than inventing the rest.

What AI model powers the recommendations?

GPT-5.6 Luna is the default in every edition, and GPT-6.2 Sol is included with Team and Enterprise. Both are hosted on Microsoft Foundry in Azure. With your own AI endpoint (Pro, Team and Enterprise), you can also use GPT models deployed in Azure OpenAI or Claude models deployed in Microsoft Foundry.

Which editions include Locking and Blocking Analysis?

All of them, including the Free edition. The editions differ in monthly analyses, servers and AI models, not in tuning goals.

Get started

Get AI SQL Tuner Studio from the Microsoft Store, or download the Free edition or a 14-day trial of any paid edition, and run the Locking and Blocking Analysis goal against any user database on SQL Server, Azure SQL Database, Azure SQL Managed Instance, SQL database in Microsoft Fabric or Amazon RDS.

Get AI SQL Tuner Studio →