SqlBLT Guide
1. Overview
SqlBLT logs blocking and long running query requests to a local database for SQL Server versions 2016+.
The SqlBLT Portal app and API reveal sources of blocking and long running queries to humans and AI agents.
By default, SqlBLT logs query requests every ten seconds that are:
| B | Blocked by another request |
| L | Long running queries (not involved in blocking) |
| T | Top blockers (the head of a blocking chain) |
SqlBLT logs requests that are waiting, for what, for how long, including statement text and query plans (as reusable templates), CPU utilisation, reads, writes and wait time.
Performance metrics are also captured (every 10 seconds by default) for correlation with the BLT data, including wait statistics, SQL Server performance counters, CPU, memory, schedulers, sessions, tempdb, and file IO per database.
Queries and plans are de-parameterised locally into template form by efficient In-Memory Natively Compiled Functions, allowing aggregation by de-parameterised templates rather than unique queries and plans.
Captured samples are aggregated by second, minute, hour and day over configurable dimensions. Configurable retention policies define how long raw and aggregate data is retained.
A TSQL script installs SqlBLT into the database you are connected to: a schema named SqlBLT with its tables, table types, views, functions, procedures and trigger; a schema named SqlBLTPortal with the read-only report procedures that the SqlBLT Portal calls; and the database role SqlBLT_Reader, which may execute them.
We recommend creating a Memory-Optimized Filegroup in the database you choose for SqlBLT so it can use Natively Compiled parsing functions to parse parameters from captured queries, and attributes from query plans. SqlBLT uses regular interpreted TSQL when a Memory-Optimized Filegroup is not present, but significanty slower. SqlBLT does not store data in In-Memory Tables, so its memory utilisation is very small.
Three SQL Server Agent jobs are created by the install script, all owned by sa:
SqlBLT_Collector(runs every 10 seconds)SqlBLT_Metrics(runs every 10 seconds)SqlBLT_Aggregate(runs every 10 minutes: aggregation of the samples and the metrics, and partition based archiving once daily)
Requirements
- SQL Server 2016 or later, Azure SQL Managed Instance, or Azure SQL Database. Azure SQL Database has no SQL Server Agent, so you must create and schedule the jobs yourself.
Documents
- SqlBLT Guide, this document: what SqlBLT logs, its installation, the Portal and its API, its permissions and settings.
- SqlBLT Database: every table, column, view, setting and metric of the database.
- SqlBLT Deployment: the deployment options of the Portal and its API, the authentication of users and programs, the set-up at identity providers, security, and every setting.
2. Components
- SqlBLT database: holds the SqlBLT schema, with captured sessions, aggregates (Agg_*). metrics (metric_*), and the SqlBLTPortal schema with the read-only report procedures. We recommend a dedicated database with a Memory-Optimized Filegroup for optimal performance, but SqlBLT can also run comfortably within another user database. It creates its own private schemas as described above and should not interfere with other activity within a shared database.
- SQL Server Agent jobs: SqlBLT_Collector and SqlBLT_Metrics sample the instance every 10 seconds; SqlBLT_Aggregate aggregates the data every 10 minutes and archives it once a day. You can reconfigure schedules if you prefer more or less frequently collection but we recommend 10 second intervals as suitable, even on busy databases.
- SqlBLT API: the operations under
api/v1/through which SqlBLT data is read, described for any program inapi/v1/openapi.json(OpenAPI 3.1). It runs insideSqlBLTPortal.exe, connects to SQL Server as the caller's Windows account, as a SQL login the caller supplies, or as the server's service account, and executes only the report procedures. SQL Server authenticates every connection, and a reader needs membership ofSqlBLT_Reader(section 5.2). - SqlBLT Portal:
SqlBLTPortal.exe, run as a desktop app on the user's computer, or on a server as a Windows service or an IIS site for browser access, optionally published with sign-in at the organisation's identity provider (OpenID Connect). Its page reads every report through the API. - Your AI agent, or any program: calls the API with its address and its description, and a credential: the key of the desktop app on the user's computer, its Windows account on a server with Windows authentication, or an access token of the identity provider on a published server (section 4.2).
3. Database
Database objects are created by running the script SqlBLT-install.sql.
Create or choose a database
First, create or choose a database to hold the SqlBLT schema and objects. A dedicated database is recommended, so that SqlBLT data is managed separately from your application data, but the script can also be run in an existing database. The script creates objects in two schemas: SqlBLT and SqlBLTPortal, and a database role named SqlBLT_Reader.
Why the database needs an In-Memory Optimized filegroup
SqlBLT uses In-Memory Natively Compiled Functions to efficiently de-parameterise SQL queries and query plans, converting them to templates which can be aggregated. If an In-Memory Optimized filegroup is not present in the database you install the SqlBLT schema, these functions will still work as interpreted Transact-SQL functions, but considerably slower than their Natively Compiled versions.
Create database script suggestion
This script creates a database named SqlBLT, with an In-Memory Optimized filegroup, using the SQL Server instance's default data path:
create database SqlBLT;
go
alter database SqlBLT add filegroup SqlBLT_mo contains memory_optimized_data;
go
declare @s nvarchar(max) = N'alter database SqlBLT add file (name = N''SqlBLT_mo'', filename = N'''
+ convert(nvarchar(max), serverproperty('InstanceDefaultDataPath')) + N'SqlBLT_mo'') to filegroup SqlBLT_mo;'
exec (@s);
go
Azure SQL Database and Azure SQL Managed Instance manage the Memory-Optimized filegroup themselves, so with these services create only the database. In-Memory OLTP may not be available in every service tier, for example General Purpose does not support Memory-Optimized filegroups presently. The parsing functions run interpreted in this scenario.
Install SqlBLT schema objects and SQL Server Agent jobs
- Run
SqlBLT-install.sqlin the database you have created or chosen via SSMS under a sysadmin login, so that the jobs can be created owned by sa. Set@DropExistingObjects = 1at the top of the script to drop an existing installation, including its captured data, before creating everything anew. - Compilation of In-Memory Natively Compiled Functions may take a few minutes during execution of the script. The script reports its outcome, including the number of objects, whether the parsing functions are natively compiled or interpreted, and whether each job was created.
- Make sure the SQL Server Agent service is running, so that the three jobs run.
- Confirm that collection has started:
SqlBLT.log_captureandSqlBLT.log_metricseach gain a row every 10 seconds, andSqlBLT.log_aggregatea row every 10 minutes.
Azure SQL Database
Azure SQL Database has no SQL Agent Jobs, so none are created. Schedule the jobs' work with a scheduler of your own: exec SqlBLT.Collect; and exec SqlBLT.CollectMetrics; every 10 seconds, and exec SqlBLT.Aggregate;, exec SqlBLT.AggregateMetrics; and exec SqlBLT.MaintainPartitions; every 10 minutes, as the job steps of the script do. The metrics collector reads sys.dm_db_resource_stats there for CPU, IO and memory; this branch has not been exercised yet.
Why SQL Server 2016+
SqlBLT uses features that earlier versions of SQL Server lack:
COMPRESSandDECOMPRESS, which store statement texts and query plans compressed, exist from SQL Server 2016.HASHBYTESaccepts input longer than 8,000 bytes from SQL Server 2016. SqlBLT hashes whole statement texts and query plans, and most plans are longer.- Table partitioning and page compression are available in Standard Edition from SQL Server 2016 SP1; before that, only in Enterprise and Developer editions. SqlBLT partitions its capture, aggregate and metric tables.
- Natively compiled scalar functions, which SqlBLT uses for its parsers where In-Memory OLTP is available, exist from SQL Server 2016.
SQL Server 2012 and 2008 also lack sys.dm_exec_input_buffer, and SQL Server 2008 lacks TRY_CONVERT and CONCAT.
4. Portal App
SqlBLT Portal can be used simply as a desktop app, or deployed as a Windows service or as a website under IIS, and published to the internet with sign-in at the organisation's identity provider.
Users can visualise database blocking and long running query activity in the SqlBLT Portal's purpose built "TopX" and "Timeline" reports.
It is built as an ASP.NET Core web application on Kestrel, published as a single self-contained file. It serves the report page and the SqlBLT API, through which the page reads every report (section 4.2); it runs as a Windows service when the Service Control Manager starts it, and under IIS as a process the ASP.NET Core Module starts.
4.1 Screenshots
4.1.1 TopX


The TopX portal report allows you to analyse blocking or long running query activity using a range of filter dimensions, and time ranges.
Choose Blocked, Long Running, or Top Blockers, filtering by Database, Application, Host, Login, Wait Type, or Resource, for a specific or relative time frame.
A range of Metrics can also be displayed, showing a resource consumption such as CPU utilisation, system level waits, disk stalls etc, aligned with your selected time frame.
4.1.2 Timeline


Timeline shows a swim lane, Gantt-style chart of blocking hierarchies in its top panel, with one expandable lane per top blocker.
A light bar runs from when the request started to the last poll it was observed.
A thicker, more solid bar stretches the consecutive polls in which the request was part of the blocking chain.
Hover over a bar to see more context information.
A Metrics panel is displayed below the main swim lane Gannt-style blocking hierarchies chart panel, with aligned, selectable metrics.
SQL statements and query plans are displayed in the last panel. Click the query plan to expand it.
4.1.3 Timeline zoomed to a blocking event


Timeline reports can be zoomed by clicking the top timeline and dragging your mouse to another point in the timeline.
This "zooms" the entire report, including the Metrics and Request timeline panel.
The Request timeline panel shows the changing state of a selected item from the top hierarchies panel, as requests can change status during blocking events.
4.1.4 Missing index recommendations


A green leaf marks a statement or a request for which SQL Server recommends a missing index.
In TopX the leaf is in the column Ix, beside the statement number (Stmt), in the legend under the chart and in the table. In Timeline it stands immediately to the left of the colour box of a lane.
Point at the leaf to see the index: its table, its equality, inequality and included columns, and the impact SQL Server estimates.
Click the leaf to open a window with the request and each recommendation: the statement text, the figures SQL Server reported, and the index written as a CREATE INDEX statement. The window can be moved, resized and maximised, like the query plan window.
The recommendations are collected by SqlBLT.Collect when its setting CaptureMissingIndexes is 1 (section 6.1). They are SQL Server's own recommendations: review an index against the existing indexes of its table before creating it.
4.1.5 Query plan warnings


An orange exclamation mark marks a statement or a request whose query plan carries a warning of the query optimizer: a type conversion that affects the plan (PlanAffectingConvert), columns without statistics (ColumnsWithNoStatistics), a join without a join predicate (NoJoinPredicate), or a filtered index that the statement cannot use (UnmatchedIndexes).
In TopX the mark is in the column !, beside Ix. In Timeline it stands beside the leaf of a lane.
Point at the mark to see the warnings. Click it to open a window with the request, the statement text, each warning with the column, conversion or index it names, and the other attributes of its plans.
The attributes are logged by SqlBLT.Collect when its setting QPlanLogAttributes is 1 (section 6.1).
4.1.6 Plans


The Plans report shows how the query plans of a statement performed over the time range. Its list is the TopX list, with the same filters.
Click a statement in the list. The chart below shows one circle for each of its requests, at the time the request ran, coloured by the query plan it used. The Y axis shows elapsed time, CPU, wait time or logical reads.
Click a circle, or a plan in the legend, to highlight one plan. The QPlan list in the Filters panel does the same.
The plan beside the chart is the highlighted plan, or the plan chosen in the plan shown list above it. Click the plan to open the plan viewer (section 4.1.8).
The bottom section shows the full statement text, SQL Server's missing index recommendations for the statement, and the optimizer warnings: those of the highlighted plan, or of every plan when none is highlighted.
The chart reads the 500 requests of the statement with the most wait time in the range. A request is one that SqlBLT captured: blocked, blocking or long running.
4.1.7 Plan


A Plan report follows one statement over its own time range, to show whether its query plan stays the same. Open one with the Plan report button of the plan viewer (section 4.1.8). It is docked under Plans in the menu.
Set a longer Time Range to see the plans the statement has used over days or weeks. The Plans report keeps its own range.
Click save to keep the report in the menu with its statement and plan. It is remembered in this browser. The x beside it removes it.
4.1.8 Query plan viewer


Click a plan to open the plan viewer. It is laid out like the plan viewer of SQL Server Management Studio: the statement at the top left, the inputs of each operator to its right, and arrows pointing to the operator that receives the rows.
Each operator shows its icon, its name and logical operation, its table and index, and its cost as a share of the statement. An operator that costs 5 % or more is marked in red. A yellow triangle marks a warning, and a yellow circle marks an operator that runs in parallel.
The number on an arrow is the estimated number of rows. A thicker arrow carries more rows.
Point at an operator to see its figures, object, predicates and output list. Click it to list all its properties in the panel at the right.
The lines above the plan show the statement text and, in green, SQL Server's missing index recommendation.
The viewer opens at 100 %. Zoom with the buttons or Ctrl+wheel, drag to pan, and use the navigator to move around a large plan. The figures are SQL Server's estimates from the compiled plan.
A registration names a SQL Server instance, the authentication (Windows or SQL login) and, for a SQL login, the login name; it never holds a password. Clicking the instance offers Add Database (the server's databases, those with a SqlBLT schema highlighted, or a typed name) and Edit Connection; each listed database is opened or closed from the menu, and the circle of a node expands or collapses it. A SQL login's password is typed in the Connect form when the instance connects and travels to the application for that session only, where it is held in memory while the session is open and dropped at disconnect, after four idle hours, or when the application restarts. The application writes nothing to any database, and nothing to disk except the direct app's registrations file and its key. Where the report procedures in a database are missing or older than the application needs, the menu says so under that database and names the SqlBLT script a DBA runs. Apart from Remember me, below, the browser itself may offer to save the login and password, since the Connect form is a standard password form.
Remember me. The Connect form of a SQL login has a Remember me tick box. When it is ticked, the browser keeps the password, encrypted by the application so that only the application can read it, and the instance connects without asking: when one of its databases is clicked, when the page is opened, and after its connection was dropped. When it is not ticked, the password is used for that session only and is asked for at the next connect. To stop remembering a password, open Edit Connection, untick Remember me and connect; the password box can stay empty. Removing the registration forgets the password too, and so does a login that the server refuses: the Connect form then opens with the reason.
Refresh and connections. The refresh icon of the Filters panel, and Auto at its interval, read the range of the capture again and then the report, so that a range such as the last 24 hours follows a capture that is running; a click while a report is loading replaces that request. The status beside Apply gives the time, the rows and the duration of the last refresh, and an error appears under the toolbar. The application restores a connection that was dropped, after four idle hours or a restart of the application, and repeats the request: Windows registrations, service connections and SQL logins with a remembered password reconnect by themselves; for a SQL login without one the Connect form opens for the password (Auto never opens a form). TopX reads the aggregates, which SqlBLT_Aggregate extends every 10 minutes: while they do not reach the end of the chosen range, the Time Range says how far they reach.
A hosted server can also offer service connections: SQL Server instances that the server connects to as its own account, listed for every user at the top of the menu, for sites that permit neither SQL logins nor users' Windows logins on their SQL Servers (the Deployment Guide, section 4).
4.2 The API
The SqlBLT API is the set of operations under api/v1/ through which SqlBLT data is read. The Portal's page reads every report through it, and any program can call the same operations: a script, a monitoring tool or an AI agent. Its description, api/v1/openapi.json (OpenAPI 3.1), states how to call it, what the data answers and how, and every operation, parameter and column of every result; a program needs no other document.
| Operations | What they do |
|---|---|
version, service | The server: its versions, its mode, the caller, and its service connections |
connect, databases, open, state, close, disconnect | Connect a SQL Server instance, list its databases, open a SqlBLT database and read the range of its capture |
report | The TopX report: the top statements, or other groups, of the blocked requests, the top blockers and the long running requests, by wait, elapsed time or child wait, with their series over time, SQL Server's missing index recommendations and the attributes of their query plans |
hierarchies | The Timeline report: the top blockers and the requests blocked under them, poll by poll |
warnings | The warnings of the query optimizer found in a range, each with the column, conversion or index it names, and their statements |
names | The databases, applications, hosts, logins, wait types and resource types of a range, for the filters |
statement, request, text, plan | One statement, one request sample by sample, a statement's text, a query plan |
metrics | The performance metrics of the instance |
A caller connects an instance, opens a SqlBLT database, reads the reports and closes them again. What it may read is decided by SQL Server, by the account of the connection, exactly as for a user of the page.
| Where the Portal runs | How a program authenticates |
|---|---|
| Desktop app | On the same computer, with the key of the desktop app: the header Authorization: Bearer <key>. The button API at the right of the top bar of the page opens a window with the address of the API, the address of its description and the key. |
| Windows service or IIS site | With Windows authentication, as the Windows account the program runs under. |
| Published with OpenID Connect | With an access token of the organisation's identity provider, issued for the API: Authorization: Bearer <access token>. |
An AI agent is given the address of the API, the credential, and the instruction to read openapi.json first. The description's section What the data answers, and how leads it through the blocking hierarchies, the blocked statements, the top blockers, the long running requests, the missing index recommendations and the warnings of the query optimizer. For example, in PowerShell, with the address and the key of the API window:
$h = @{ Authorization = 'Bearer <the key>' }
Invoke-RestMethod http://127.0.0.1:8781/api/v1/version -Headers $h
4.3 Deployment
The same executable serves every deployment. The SqlBLT Deployment Guide gives the steps, the settings and the security of each option, the set-up at identity providers, and the API's use by programs and AI agents.
| Desktop app | Windows service | IIS site | Published with OpenID Connect | |
|---|---|---|---|---|
| Runs | on the user's computer, as the user | on a server, as a service account | on an IIS web server, as the application pool identity | on a server, as a Windows service or an IIS site, at a public HTTPS address |
| Users sign in | not at all: the app answers its own user only | with their Windows accounts | with their Windows accounts, through IIS | at the organisation's identity provider |
| Connects to SQL Server as | the user, or a SQL login | the user (with Kerberos constrained delegation), a SQL login, or the service account for the service connections | a SQL login, the service account, or the user's Active Directory account (with Kerberos protocol transition) | |
| Programs and AI agents | the key of the desktop app | their Windows account | an access token | |
5. Security
5.1 Collector permissions
The three jobs are owned by sa and already hold every permission; the permissions below matter only when the collector runs under another login, for example a scheduler on Azure SQL Database, where VIEW DATABASE STATE replaces VIEW SERVER STATE.
- The collector and metrics jobs run by the SQL Server Agent jobs need VIEW SERVER STATE (VIEW SERVER PERFORMANCE STATE on SQL Server 2022 and later), CONNECT ANY DATABASE and VIEW ANY DEFINITION.
- Page-resource resolution on SQL Server 2016 and 2017 uses DBCC PAGE, which needs sysadmin; without sysadmin that step is skipped.
5.2 Portal user database permissions
The install script creates a database role, SqlBLT_Reader, with execute permission on the SqlBLTPortal schema; the report procedures read the SqlBLT tables on the role's behalf, and nothing else is granted.
Create a Windows Group in your Active Directory, with a matching SQL Server Login, and a database user enrolled in the database role described below. This provides minimum permissions necessary for users to access the SqlBLT data and execute stored procedures needed to use the SqlBLT Portal app.
A database role for SqlBLT readers
The script creates the role with one grant, shown here for reference; add members to the role rather than granting each login. Nothing is granted on the SqlBLT tables, the collector, the aggregation or the partition maintenance, so a member can neither read the captured data directly nor change anything.
use SqlBLT;
create role SqlBLT_Reader;
grant execute on schema::SqlBLTPortal to SqlBLT_Reader;
Users: a Windows group
We recommend a Windows group for the people who use the SqlBLT Portal: add their Windows logins to the group, give the group one login on each SQL Server instance, and add it to SqlBLT_Reader in each SqlBLT database. The same group serves every mode: the desktop app connects as each user's own Windows account; a Windows service or web site connects as the signed-in user with --impersonate, and its AllowedGroup can name the same group. Adding or removing a person is then a change to the group, with nothing to change in SQL Server. A service connection's service account, or a SQL login, is added to the role the same way.
create login [DOMAIN\SqlBLT Users] from windows;
go
use SqlBLT;
create user [DOMAIN\SqlBLT Users] for login [DOMAIN\SqlBLT Users];
alter role SqlBLT_Reader add member [DOMAIN\SqlBLT Users];
Programs and AI agents
A program or an AI agent reads SqlBLT data through the API (section 4.2), which connects with the same credentials as a user, so SqlBLT_Reader is all it needs. Give it a Windows account or a SQL login of its own, with a login on each instance and membership of the role, so that its access is granted, audited and revoked apart from the users'.
use SqlBLT;
create user [DOMAIN\agent account] for login [DOMAIN\agent account];
alter role SqlBLT_Reader add member [DOMAIN\agent account];
5.3 Portal access models
The Portal never stores a credential. A SQL login's password is held in memory while its connection is open, and with Remember me kept by the user's browser, encrypted by the Portal with Windows data protection (DPAPI) so that only that Portal can read it. A Windows registration is the user's own identity: on the user's computer directly, from a Windows service or IIS site by Kerberos constrained delegation, and from a published Portal by Kerberos protocol transition. A service connection involves no credential of the user at all. The connection ids the page and programs hold are random and bound to the caller who opened them, so one caller cannot use another's connection.
| Who | Is authenticated by | Is allowed by |
|---|---|---|
| A user of the desktop app | Windows, as the user who runs it; the app answers its own user only | SQL Server |
| A user of a Windows service or IIS site | Windows authentication (Kerberos or NTLM) | the Windows group of AllowedGroup or IIS, then SQL Server |
| A user of a published Portal | the organisation's identity provider (OpenID Connect), with its own policies such as multi-factor authentication | a claim of the identity provider (AllowedClaim), then SQL Server |
| A program | the key of the desktop app, Windows authentication, or an access token of the identity provider | as a user |
A published Portal adds HTTPS only, protections against requests from other sites, connections by TCP only, a limit on refused SQL logins, and an audit log in the Windows event log. The Deployment Guide, section 10, describes where each credential is held, the constraints a site may set, the network, and the residual risks.
6. Configuration
6.1 Key settings
SqlBLT is configured mainly in the table SqlBLT.config_setting, which has one row per setting of each procedure. A procedure reads its settings at the start of every execution, so a changed value applies from its next execution. How often SqlBLT samples and aggregates is set by the schedules of its three SQL Server Agent jobs, and how long data is kept by the table SqlBLT.config_partition.
The Portal's own settings, its command line and appsettings.json, are listed in the Deployment Guide, section 11.
Filter. WaitTimeFilterMS of Collect, 10 milliseconds as installed, decides what is logged: a blocking hierarchy, with all its sessions, when one of its blocked requests has waited longer than this, and a long running request when it is older than this. For example, to log only what has waited or run for more than one second:
update SqlBLT.config_setting set value = 1000
where procedure_name = N'Collect' and setting_name = N'WaitTimeFilterMS';
Statement texts and query plans. Four settings of Collect, each 1 as installed, choose whether statement texts and query plans are de-parameterised, and whether they are stored as captured:
| Setting | 1 | 0 |
|---|---|---|
ParseSqlText | Each statement text is de-parameterised and stored as its template. Texts that differ only in their literals are one statement. | The SQL parser is not run. Each distinct text is a statement of its own. |
ParseQPlans | Each query plan is de-parameterised and stored as its template. | The plan parser is not run. Each distinct plan fetched is a plan of its own. With QPlanSkipStorageOfKnownHashes = 1, as installed, a plan is not stored again when its query_plan_hash already has one. |
StoreSqlTextSample | The text as captured is stored. With ParseSqlText = 1 it is the first original text of each template, kept as a sample. | The text as captured is not stored. |
StoreQPlanSample | The plan as captured is stored. With ParseQPlans = 1 it is the first original plan of each template, kept as a sample. | The plan as captured is not stored. |
With ParseSqlText = 0 and StoreSqlTextSample = 0 no text is stored, and with ParseQPlans = 0 and StoreQPlanSample = 0 no plan: the statement or plan is still counted. A changed value applies to the texts and plans that have not been captured before. Further settings of Collect shape the templates:
QPlanSkipStorageOfKnownHashes: 1 (as installed) = the plan of a statement whosequery_plan_hashalready has a template is not parsed or stored again; 0 = every distinct plan is parsed.KeepDatabaseNames,KeepSchemaNamesandKeepObjectNames: 1 (as installed) = the names stay in the templates; 0 = each name becomes ?, so that statements which differ only in such names share one template.
Missing index recommendations. CaptureMissingIndexes of Collect, 1 as installed, stores the missing index recommendations that SQL Server holds for the queries of the requests it logs: the table of the index, its equality, inequality and included columns, and the estimated impact. On SQL Server 2019 and later they are read from sys.dm_db_missing_index_group_stats_query at every poll, and the index of a recommendation from sys.dm_db_missing_index_details once, when it is first found. On SQL Server 2016 and 2017 they are read from each query plan a poll fetches: with QPlanLogAttributes = 1 every plan is fetched at every poll; with 0, and QPlanSkipStorageOfKnownHashes = 1, a plan is fetched once per query_plan_hash, so a recommendation is found when its plan is first fetched. The recommendations are kept in SqlBLT.ref_missing_index and SqlBLT.ref_query_missing_index, and the SqlBLT Portal marks the statements and requests that have one with a green leaf. SqlBLT.log_capture records, for every poll, the time spent on them in ms_missing_index and their number in missing_indexes, so that the cost of the setting can be measured with it on and off. To stop reading them:
update SqlBLT.config_setting set value = 0
where procedure_name = N'Collect' and setting_name = N'CaptureMissingIndexes';
Query plan attributes. QPlanLogAttributes of Collect, installed by default as 1 but configurable by changing its row of SqlBLT.config_setting, fetches the plan of every request logged at every poll and logs what the plan carries besides its shape: the warnings of the query optimizer (PlanAffectingConvert, ColumnsWithNoStatistics, NoJoinPredicate, UnmatchedIndexes), the plan guide, the reason for a serial plan, the reason for an early end of optimization, the cardinality estimation model, and the compile time, CPU and memory. With 0 they are not logged, and a plan is fetched only to be stored. SqlBLT.log_capture records the time of the step for every poll in ms_qplan_attribute.
Retention. SqlBLT.config_partition has one row per partition function. partitions_retained is the number of partitions before the current one that keep their rows; a partition holds one day as installed, so it is a number of days. SqlBLT.MaintainPartitions applies it once a day, in its first execution at or after the hour DailyCleanupAfterHour (1 as installed), by truncating the partitions that are no longer retained. It then deletes the statement texts and query plans that no row references any more: SqlBLT.ref_counts holds the number of references to each of them, so the delete does not depend on how much data is retained.
| Partition function | Table | Partitions retained |
|---|---|---|
pfSqlBLT | SqlBLT.session_base | 14 |
pfSqlBLTSecond | SqlBLT.agg_second | 14 |
pfSqlBLTMinute | SqlBLT.agg_minute | 90 |
pfSqlBLTHour | SqlBLT.agg_hour | 183 |
pfSqlBLTDay | SqlBLT.agg_day | 365 |
pfSqlBLTMetric | SqlBLT.metric_base | 14 |
pfSqlBLTMetricMinute | SqlBLT.metric_minute | 90 |
pfSqlBLTMetricHour | SqlBLT.metric_hour | 183 |
pfSqlBLTMetricDay | SqlBLT.metric_day | 365 |
For example, to keep the captured rows for 30 days:
update SqlBLT.config_partition set partitions_retained = 30
where function_name = N'pfSqlBLT';
Database size. Once a day, after the retention, SqlBLT.MaintainPartitions logs the size of every SqlBLT table in SqlBLT.size_table and of each partition that holds rows in SqlBLT.size_partition: the rows and, in KB, the space reserved, the data, the indexes and the unused space, counted as sp_spaceused counts them. SqlBLT.size_object names the tables and gives each its data type from SqlBLT.size_type: the statement texts, the query plans, and the BLT data and the metrics at each grain. The log shows how the database grows and what a day of each table costs, which is what a retention is chosen from. For example, the latest sizes by data type (the row without a type is the other tables: dictionaries, logs, configuration and state), the size of each day of the captured rows, and the size of all tables at each daily execution:
select t.typename, t.grain, tables = count(*), rows = sum(s.rows), reserved_mb = sum(s.reserved_kb) / 1024
from SqlBLT.size_table s
join SqlBLT.size_object o on o.objid = s.objid
left join SqlBLT.size_type t on t.typeid = o.typeid
where s.maint_id = (select max(maint_id) from SqlBLT.size_table)
group by t.typeid, t.typename, t.grain
order by isnull(t.typeid, 999);
select day = convert(date, p.range_from), p.rows, p.reserved_kb
from SqlBLT.size_partition p
join SqlBLT.size_object o on o.objid = p.objid
where o.objname = N'session_base' and p.maint_id = (select max(maint_id) from SqlBLT.size_partition)
order by p.part_id;
select logged = convert(date, m.started), reserved_mb = sum(s.reserved_kb) / 1024
from SqlBLT.size_table s
join SqlBLT.log_maintenance m on m.maint_id = s.maint_id
group by m.maint_id, m.started
order by m.maint_id;
Frequency. The schedules of the jobs set how often SqlBLT runs: SqlBLT_Collector and SqlBLT_Metrics every 10 seconds and SqlBLT_Aggregate every 10 minutes as installed. Change a schedule in SQL Server Agent. When the collector is scheduled less often than every 60 seconds, raise MaxPollGapSeconds to its interval: a poll counts the work of at most that many seconds since the previous poll.
Metrics and aggregates. The column enabled of SqlBLT.metric says which metrics are collected, and the column enabled of SqlBLT.agg_set which sets of dimensions are aggregated.
6.2 All settings
The rows of SqlBLT.config_setting, with the values installed. Each setting is a parameter of its procedure; to change one, update value in its row.
| Procedure | Setting | Value | What it does |
|---|---|---|---|
SqlBLT.Collect | WaitTimeFilterMS | 10 | Milliseconds. A blocking hierarchy is logged, with all its sessions, when one of its blocked requests has waited longer than this; a long running request is logged when it is older than this. |
SqlBLT.Collect | PageIOLatchLookupBudgetMS | 5000 | Milliseconds per poll for finding the objects of the pages that requests in PAGEIOLATCH waits wait for; further lookups in that poll are skipped. 0 = no lookup. |
SqlBLT.Collect | MaxSleepingBatchChars | 8000 | Characters of text kept for a sleeping head blocker, whose only text is its whole most recent batch. |
SqlBLT.Collect | KeepDatabaseNames | 1 | Text and plan templates: 1 = database names stay; 0 = each database name becomes ? (system databases stay). |
SqlBLT.Collect | KeepSchemaNames | 1 | Text and plan templates: 1 = schema names stay; 0 = each schema name becomes ? (dbo, sys and INFORMATION_SCHEMA stay). |
SqlBLT.Collect | KeepObjectNames | 1 | Text and plan templates: 1 = object names stay; 0 = each table, view, function, procedure and index name becomes ? (sys objects and sp_ and xp_ names stay). |
SqlBLT.Collect | ParseSqlText | 1 | 1 = each statement text is de-parameterised and stored as its template; 0 = the SQL parser is not run, and each distinct text as captured is a statement of its own. |
SqlBLT.Collect | StoreSqlTextSample | 1 | 1 = the text as captured is stored: with ParseSqlText = 1, the first original text of each template, as a sample; 0 = it is not stored. |
SqlBLT.Collect | QPlanStatementText | 2 | The statement text inside a plan template: 0 = removed; 1 = the original text kept; 2 = the parsed text kept. |
SqlBLT.Collect | QPlanKeepMissingIndexes | 0 | Missing index suggestions inside a plan template: 0 = removed; 1 = kept, with their impact set to 0. |
SqlBLT.Collect | ParseQPlans | 1 | 1 = each query plan is de-parameterised and stored as its template; 0 = the plan parser is not run, and each distinct plan fetched is a plan of its own: with QPlanSkipStorageOfKnownHashes = 1 a plan is not stored again when its query_plan_hash already has one. |
SqlBLT.Collect | StoreQPlanSample | 1 | 1 = the plan as captured is stored: with ParseQPlans = 1, the first original plan of each template, as a sample; 0 = it is not stored. |
SqlBLT.Collect | QPlanSkipStorageOfKnownHashes | 1 | 1 = the plan of a statement whose query_plan_hash already has a template is not parsed or stored again, and its rows use that template; 0 = every distinct plan is parsed. |
SqlBLT.Collect | QPlanLogAttributes | 1 | 1 = the plan of every request logged is fetched at every poll and its attributes are logged; 0 = they are not logged, and a plan is fetched only to be stored. |
SqlBLT.Collect | MaxPollGapSeconds | 60 | Seconds. The window of a poll is the time since the previous poll, at most this; the work stored with a row is the work of its request and its statement in that window. |
SqlBLT.Collect | CaptureMissingIndexes | 1 | The missing index recommendations of SQL Server for the queries of the requests logged: 1 = they are stored (SQL Server 2019 and later: read from sys.dm_db_missing_index_group_stats_query at every poll; SQL Server 2016 and 2017: read from each plan a poll fetches); 0 = they are not read. |
SqlBLT.CollectMetrics | MaxIntervalSeconds | 3600 | Seconds. When the previous run is older than this, the run stores no growth figures and starts afresh. |
SqlBLT.CollectMetrics | SkipIdleDatabaseIO | 1 | 1 = the file IO row of a database without activity in the interval is not stored, and the aggregates count the missing row as zero; 0 = it is stored. |
SqlBLT.Aggregate | MaxPollsPerBatch | 30 | Polls aggregated per batch. |
SqlBLT.Aggregate | MaxBatches | 20 | Batches per execution. |
SqlBLT.Aggregate | StatementFirstSampleNull | 0 | The first sample of a statement: 1 = it adds nothing to the statement sums of CPU time, reads and writes; 0 = it adds the increments of its request to them. |
SqlBLT.AggregateMetrics | MaxPollsPerBatch | 120 | Metric runs aggregated per batch. |
SqlBLT.AggregateMetrics | MaxBatches | 50 | Batches per execution. |
SqlBLT.AggregateMetrics | InMemoryWorkTables | 0 | Where a batch is staged: 0 = temporary tables; 1 = the memory-optimized tables SqlBLT.metric_agg_polls and SqlBLT.metric_agg_rows, created when missing. |
SqlBLT.MaintainPartitions | DailyCleanupAfterHour | 1 | Hour of the day, 0 to 23. The first execution at or after this hour does the partition maintenance of the day; every other execution exits. |
SqlBLT.MaintainPartitions | DeleteOrphanedSQLText | 1 | 1 = the text templates that no row references any more are deleted: those without a reference count in SqlBLT.ref_counts. |
SqlBLT.MaintainPartitions | DeleteOrphanedQPlans | 1 | 1 = the plan templates that no row references any more are deleted: those without a reference count in SqlBLT.ref_counts. |
SqlBLT.MaintainPartitions | MaxRetriesPerDay | 3 | After a failed execution: the number of further executions of that day that try again. 0 = none before the next day. |
SqlBLT.MaintainPartitions | RebuildRefCountsDayOfMonth | 0 | Day of the month, 1 to 31: the execution of that day rebuilds the reference counts of SqlBLT.ref_counts from the rows (in a month with fewer days, on its last day). 0 = no monthly rebuild. |
SqlBLT.MaintainPartitions | RebuildRefCountsDayOfWeek | 0 | Day of the week, 1 = Monday to 7 = Sunday: the execution of that day rebuilds the reference counts from the rows. 0 = no weekly rebuild. |
7. Sources
The SQL Server Agent jobs collect from these sources.
SqlBLT_Collector job
sys.dm_exec_requests- Running requests, their waits and blockers.
sys.dm_exec_sessions- Login, host, program and session settings.
sys.dm_exec_connections- Client address, protocol and last SQL handle.
sys.sysprocesses- Legacy command, wait type and open transactions.
sys.dm_os_waiting_tasks- Wait resources of blocked tasks.
sys.dm_tran_session_transactions- Open transactions of each session.
sys.dm_tran_active_transactions- Transaction names and begin times.
sys.dm_tran_database_transactions- Time of each transaction's first log record.
sys.dm_exec_sql_text- Batch and statement text.
sys.dm_exec_input_buffer- Input buffer where statement text is unavailable.
sys.dm_exec_text_query_plan- Statement query plans, and the attributes they carry; on SQL Server 2016 and 2017 also the missing index recommendations inside them.
sys.dm_db_missing_index_group_stats_query,sys.dm_db_missing_index_groups,sys.dm_db_missing_index_details- Missing index recommendations for the queries of the requests logged, SQL Server 2019 and later.
sys.dm_db_page_info- Object of a waited-on page, SQL Server 2019 and later.
DBCC PAGE- Object of a waited-on page, SQL Server 2016 and 2017, sysadmin only.
sys.partitions,sys.allocation_units,sys.objects,sys.schemas,sys.indexes- Names of locked objects and indexes, read in their own database.
OBJECT_NAME,OBJECT_SCHEMA_NAME- Names of the modules that contain statements.
SqlBLT_Metrics job
sys.dm_os_wait_stats- Wait time by wait type.
sys.dm_os_performance_counters- SQL Server performance counters.
sys.dm_os_ring_buffers- SQL Server, other process and idle CPU.
sys.dm_db_resource_stats- Resource use on Azure SQL Database.
sys.dm_os_schedulers- Runnable tasks, workers and pending IO.
sys.dm_exec_query_resource_semaphores- Memory grants waiting and granted.
sys.dm_os_process_memory- SQL Server memory in use.
sys.dm_exec_sessions,sys.dm_exec_requests- Counts of user sessions and active, blocked and waiting requests.
tempdb.sys.dm_db_file_space_usage- tempdb version store, object and free space.
sys.dm_io_virtual_file_stats,sys.master_files- File IO per database, data and log apart.
sys.databases- Database names.
sys.dm_os_sys_info- Instance start time, to detect restarts.
8. Data model
SqlBLT keeps its data in the schema SqlBLT: 52 tables and 5 views, in eight groups.
| Group | Tables | Holds |
|---|---|---|
| Capture | session_base, request_state | One row per sampled session per poll: the blocked requests (B), the heads of blocking chains (T) and the long running requests (L), each with its wait, the resource waited for, its statement and plan, and its work since the previous poll. request_state keeps each request's last counters for that calculation. |
| Dictionaries and templates | ref_type, ref_value, ref_sqltext, ref_sqltext_key, ref_qplan, ref_qplan_key, ref_qplan_hash, ref_request, ref_counts, ref_missing_index, ref_query_missing_index | Each name or value once (database, host, login, program, wait type, resource and others), referred to by id; each statement text and each query plan once, as a de-parameterised template; each request once; the number of references that the rows hold to each text, plan and value; the missing index recommendations of SQL Server for the queries of the requests logged. |
| Query plan attributes | ref_qplan_value, ref_qplan_attribute, ref_qplan_time, ref_qplan_column, ref_qplan_index, ref_qplan_convert, ref_qplan_att_no_statistics, ref_qplan_att_convert, ref_qplan_att_unmatched_index, ref_query_qplan_attribute | What the plan of a request carries besides its shape: the warnings of the query optimizer with the columns, conversions and indexes they name, the plan guide, the reasons and the compile values; each text value once. |
| Aggregates | agg_second, agg_minute, agg_hour, agg_day, agg_set, agg_dimension | Samples, sums and maxima of the captured rows per second, minute, hour and day, for each enabled set of dimensions. |
| Metrics | metric, metric_base, metric_minute, metric_hour, metric_day, metric_scope, metric_state, metric_wait_skip, metric_agg_polls, metric_agg_rows | The 115 metrics of metric, sampled at every run and aggregated per minute, hour and day. |
| Config | config_setting, config_partition, config_version | The settings of the procedures, the boundary period and the retention of each partition function, and the versions installed. |
| Logging | log_capture, log_capture_error, log_aggregate, log_metrics, log_metrics_aggregate, log_metrics_error, log_maintenance, log_maintenance_partition | One row per poll, metrics run, aggregation batch and maintenance execution, with its timings and outcome; the errors. |
| Size | size_type, size_object, size_table, size_partition | The size log: the size of every table and of each daily partition that holds rows, logged once a day by the daily maintenance, and the data type of each table. |
SqlBLT.Collect(every 10 seconds) writes the sampled sessions tosession_base. Each name or value goes toref_valueonce and is stored as its id; each statement text and query plan is de-parameterised and stored once inref_sqltextandref_qplan. The missing index recommendations of SQL Server for the queries of those sessions are stored inref_missing_index, each index once, andref_query_missing_index, once per statement and query. The attributes of the plans of those sessions are stored in the tables of the query plan attributes: each combination, column, conversion, index and text value once.SqlBLT.Aggregate(every 10 minutes) adds the new polls toagg_second,agg_minute,agg_hourandagg_day, for each enabled set of dimensions inagg_set.ref_countsholds the number of references that the rows ofsession_baseand of the four aggregate tables hold to each statement text, query plan and dictionary value.SqlBLT.CollectandSqlBLT.Aggregateadd to it in the transaction that inserts their rows.SqlBLT.CollectMetrics(every 10 seconds) writes the metric samples tometric_base;SqlBLT.AggregateMetrics(every 10 minutes) adds them tometric_minute,metric_hourandmetric_day.SqlBLT.MaintainPartitions(once a day) keeps the partitions: the capture, aggregate and metric tables are partitioned by day, and the partitions older than the retention inconfig_partitionare truncated. The references of the truncated rows are taken offref_counts, and the statement texts and query plans left without a reference are deleted, with the missing index recommendations of those texts and the attributes of those plans. It then logs the size of every table insize_tableand of each partition that holds rows insize_partition.- The report procedures of the schema
SqlBLTPortalread these tables for the SqlBLT Portal; they change nothing.
An installation has no foreign key constraints by default, but can be created by executing the stored procedureSqlBLT.SetForeignKeys which creates or drops the 137 foreign keys, all of them or those of the tables of one section (capture, dictionaries, aggregates, metrics, logging, size), for whoever wants the database to enforce or to show its structure. With the foreign keys in place every insert looks up the rows it references, and SqlBLT works the same and writes faster without them. On a database that holds rows, stop the three jobs before creating them. For example, to create them all and validate the rows present, and to drop them again:
exec SqlBLT.SetForeignKeys @Enable = 1;
exec SqlBLT.SetForeignKeys @Enable = 0;
Every table, column, view, setting and metric is described in the SqlBLT Database.
8.1 Entity relationship diagram
8.2 Data flow
Where each column of SqlBLT.session_base and each metric comes from, and which columns the aggregation reads.