Skip to main content

Microsoft SQL Server

Microsoft SQL Server

Plugin: go.d.plugin Module: mssql

Maintained by Netdata

Overview

Monitor Microsoft SQL Server performance, databases, SQL Server Agent jobs, replication, and Always On Availability Groups. Charts cover connections, throughput, buffer and memory pressure, waits and locks, per-database transactions and transaction logs, and the health of every job, publication, and availability group.

All SQL Server editions (Express, Web, Standard, Enterprise, Developer) and Azure SQL Managed Instance are supported. Azure SQL Database is not supported: required instance-level memory and file views are unavailable, so the job cannot start. Charts appear only for what the instance actually has and the monitoring login can read:

AreaCharts appear
Instance: connections, batch requests, compilations, SQL errors, buffer manager, memory, process and OS memoryAlways
Database: transactions, transaction log usage and growth, data and log file sizes, I/O stall, stateFor every database
Locks and waitsFor every lock resource type and wait type observed
SQL Server Agent jobs: enabled state, last execution result, duration, age, current run timeWhen the instance has SQL Server Agent (not on Express) and the login can read msdb
Replication: publication status, warnings, latency, subscriptionsWhen the instance is a distributor and the login can read the distribution database
Always On Availability Groups: group, replica, database replica, WSFC cluster health, automatic page repairWhen Always On is enabled on the instance

Three Functions add on-demand troubleshooting from the dashboard: top-queries lists the most expensive query patterns from Query Store or the plan cache, deadlock-info shows the most recent deadlock graph, and error-info lists recent SQL errors from an Extended Events session. See Live Data below.

The collector connects to the instance over TCP with the Tabular Data Stream (TDS) protocol, using the dsn connection string. It authenticates with a SQL Server login, with Windows integrated authentication when the DSN carries no credentials (Windows only), or with a Microsoft Entra ID token when cloud_auth is configured for Azure SQL Managed Instance.

Every update_every seconds it runs read-only queries against system views on one connection, each bounded by timeout:

AreaViews
Counters, sessions, waits, lockssys.dm_os_performance_counters, sys.dm_exec_sessions, sys.dm_exec_requests, sys.dm_os_wait_stats, sys.dm_tran_locks
Memory and filessys.dm_os_process_memory, sys.dm_os_sys_memory, sys.dm_io_virtual_file_stats, sys.master_files, sys.databases
SQL Server Agentmsdb.dbo.sysjobs, msdb.dbo.sysjobhistory, msdb.dbo.sysjobactivity
Replicationdistribution.dbo.MSreplication_monitordata, distribution.dbo.MSpublications, distribution.dbo.MSsubscriptions
Always Onsys.availability_groups, sys.availability_replicas, and the sys.dm_hadr_* views for group, replica, database, cluster, failover readiness, page repair and thread state

Functions open a second connection the first time one is used, keeping the metrics connection available. Both workloads still share SQL Server CPU, I/O and locks. The collector never writes to the server: it creates no objects, changes no settings, and leaves the Extended Events sessions it reads untouched.

This collector is supported on all platforms.

This collector supports collecting metrics from multiple instances of this integration, including remote instances.

The monitoring login needs these grants. VIEW SERVER STATE is the only mandatory one; without an optional grant the collector keeps running and omits the affected charts.

GrantNeeded for
VIEW SERVER STATEAll metrics (dynamic management views and performance counters). On SQL Server 2022 and later the narrower VIEW SERVER PERFORMANCE STATE can be granted instead.
VIEW ANY DEFINITIONData file size and I/O stall values (read through sys.master_files; without it those charts exist but stay empty) and Always On Availability Group charts (availability group catalog views)
SELECT on msdb.dbo.sysjobsSQL Server Agent job status chart
SELECT on msdb.dbo.sysjobhistory and msdb.dbo.sysjobactivitySQL Server Agent job execution charts
SELECT on distribution.dbo.MSreplication_monitordata, MSpublications and MSsubscriptionsReplication charts (distributor instances only)
VIEW DATABASE STATE (SQL Server 2016 to 2019) or VIEW DATABASE PERFORMANCE STATE (2022 and later) in each user databasetop-queries reading Query Store; see the Function's prerequisites under Live Data

The login only reads. No ALTER, EXECUTE, or write permission is needed.

Microsoft SQL Server can be monitored further using the following other integrations:

Default Behavior

Auto-Detection

This integration doesn't support auto-detection.

Limits

  • SQL Server Agent execution charts (last result, duration, age, current run time) are created only for enabled jobs. Disabled jobs keep their status chart; set collect_disabled_jobs: yes to chart their executions too.
  • The current run time of a job comes from the latest SQL Server Agent activity session, so a job whose run was cut short by an Agent service crash can show as running until Agent starts a new session.
  • A job that succeeded with failed intermediate steps is reported as warning only while that step history still exists; if the history is purged before collection, it is reported as ok.
  • top-queries returns at most functions.top_queries.limit query patterns (500) from the last functions.top_queries.time_window_days days (7), with query text cut at 4096 characters. error-info returns at most the same number of rows. deadlock-info returns only the most recent deadlock.

Performance Impact

Negligible on the Agent host. On the monitored instance, each collection runs about 20 to 30 lightweight queries on one connection against in-memory counters and system views; the per-database and Always On queries grow with the number of databases and replicas but typically finish in milliseconds. Raise update_every to lower the query rate.

Functions are heavier and run only when requested: top-queries aggregates Query Store runtime statistics or scans the plan cache, and error-info and deadlock-info read Extended Events files, which for the built-in system_health session can hold about 1 GB. They use a separate connection but compete with your workload for SQL Server CPU and I/O. Lower functions.top_queries.time_window_days, or set functions.<name>.disabled: yes for Functions you do not need.

Setup

You can configure the mssql collector in two ways:

MethodBest forHow to
UIFast setup without editing filesGo to Nodes → Configure this node → Collectors → Jobs, search for mssql, then click + to add a job.
FileIf you prefer configuring via file, or need to automate deployments (e.g., with Ansible)Edit go.d/mssql.conf and add a job.
important

UI configuration requires paid Netdata Cloud plan.

Prerequisites

Create a monitoring login

For SQL authentication, create a login with the grants below. Skip this step if you use Windows Authentication or Microsoft Entra ID (next steps). SQL logins need the instance to run in mixed authentication mode ("SQL Server and Windows Authentication mode").

CREATE LOGIN netdata_user WITH PASSWORD = 'YourStrongPassword!';
GRANT VIEW SERVER STATE TO netdata_user;
-- Data file sizes, I/O stall, and Always On Availability Groups
GRANT VIEW ANY DEFINITION TO netdata_user;

-- SQL Server Agent jobs (skip on Express, which has no Agent)
USE msdb;
CREATE USER netdata_user FOR LOGIN netdata_user;
GRANT SELECT ON dbo.sysjobs TO netdata_user;
GRANT SELECT ON dbo.sysjobhistory TO netdata_user;
GRANT SELECT ON dbo.sysjobactivity TO netdata_user;

-- Replication (distributor instances only)
USE distribution;
CREATE USER netdata_user FOR LOGIN netdata_user;
GRANT SELECT ON dbo.MSreplication_monitordata TO netdata_user;
GRANT SELECT ON dbo.MSpublications TO netdata_user;
GRANT SELECT ON dbo.MSsubscriptions TO netdata_user;

To verify, run the collector's first query as the new login; it must return a row:

EXECUTE AS LOGIN = 'netdata_user';
SELECT TOP 1 counter_name FROM sys.dm_os_performance_counters;
REVERT;

Grant Windows Authentication access

Only when the DSN carries no username and password (Windows only). The Netdata service then authenticates with its own Windows account, Local System by default, and that account needs a SQL Server login.

For an instance on the same machine, Local System is seen as NT AUTHORITY\SYSTEM:

CREATE LOGIN [NT AUTHORITY\SYSTEM] FROM WINDOWS;
GRANT VIEW SERVER STATE TO [NT AUTHORITY\SYSTEM];
GRANT VIEW ANY DEFINITION TO [NT AUTHORITY\SYSTEM];
USE msdb;
CREATE USER [NT AUTHORITY\SYSTEM] FOR LOGIN [NT AUTHORITY\SYSTEM];
GRANT SELECT ON dbo.sysjobs TO [NT AUTHORITY\SYSTEM];
GRANT SELECT ON dbo.sysjobhistory TO [NT AUTHORITY\SYSTEM];
GRANT SELECT ON dbo.sysjobactivity TO [NT AUTHORITY\SYSTEM];

For an instance on another machine, a domain-joined Netdata host is seen as its computer account, DOMAIN\COMPUTERNAME$ (for example MYDOM\SQLBOX01$):

CREATE LOGIN [DOMAIN\COMPUTERNAME$] FROM WINDOWS;
GRANT VIEW SERVER STATE TO [DOMAIN\COMPUTERNAME$];
GRANT VIEW ANY DEFINITION TO [DOMAIN\COMPUTERNAME$];
USE msdb;
CREATE USER [DOMAIN\COMPUTERNAME$] FOR LOGIN [DOMAIN\COMPUTERNAME$];
GRANT SELECT ON dbo.sysjobs TO [DOMAIN\COMPUTERNAME$];
GRANT SELECT ON dbo.sysjobhistory TO [DOMAIN\COMPUTERNAME$];
GRANT SELECT ON dbo.sysjobactivity TO [DOMAIN\COMPUTERNAME$];

Local System cannot authenticate to a remote instance from a workgroup machine. Run the Netdata service as a domain account instead, or use a SQL login. To see which account SQL Server receives, connect with Windows Authentication and run SELECT SYSTEM_USER.

Grant a Microsoft Entra identity access to Azure SQL Managed Instance

Only when cloud_auth.provider is azure_ad. The service principal or managed identity that Netdata signs in with needs a login created from the external provider, named after the app registration or the managed identity. Create database users and grant the optional database permissions listed above for SQL Server Agent jobs and replication. See Microsoft's guide to Microsoft Entra authentication for Azure SQL.

-- Azure SQL Managed Instance
CREATE LOGIN [netdata-monitoring] FROM EXTERNAL PROVIDER;
GRANT VIEW SERVER STATE TO [netdata-monitoring];
GRANT VIEW ANY DEFINITION TO [netdata-monitoring];

Configuration

Options

The following options can be defined globally: update_every, autodetection_retry.

Config options
GroupOptionDescriptionDefaultRequired
Baseupdate_everyData collection interval, in seconds.10no
autodetection_retryHow often to retry the initial connection when the job fails to start, in seconds. Zero disables retries.0no
dsnConnection string in go-mssqldb DSN format, such as sqlserver://user:password@host:1433. With cloud_auth.provider set to azure_ad, only the sqlserver:// URL form is accepted.sqlserver://localhost:1433yes
timeoutQuery timeout, in seconds.5no
vnodeAssociates this job with a Virtual Node.no
SQL Agentcollect_disabled_jobsAlso create execution charts for disabled SQL Server Agent jobs. The enabled/disabled status chart always covers every job.nono
Cloud Authcloud_auth.providerAuthentication provider for Azure SQL Managed Instance. none uses the credentials in dsn; azure_ad signs in with a Microsoft Entra ID token.noneno
cloud_auth.azure_ad.modeHow Netdata obtains the Microsoft Entra ID token. service_principal uses an app registration with a client secret, managed_identity the identity of the Azure resource running Netdata, and default the Azure SDK credential chain.defaultyes
cloud_auth.azure_ad.mode_service_principal.tenant_idDirectory (tenant) ID of the Microsoft Entra tenant that holds the service principal. Required in service_principal mode.no
cloud_auth.azure_ad.mode_service_principal.client_idApplication (client) ID of the service principal. Required in service_principal mode.no
cloud_auth.azure_ad.mode_service_principal.client_secretClient secret of the service principal. Required in service_principal mode.no
cloud_auth.azure_ad.mode_managed_identity.client_idClient ID of a user-assigned managed identity. Leave empty to use the system-assigned identity of the Azure resource.no
Functionsfunctions.top_queries.disabledDisable the top-queries Function.nono
functions.top_queries.timeoutQuery timeout for top-queries requests, in seconds, independent of the metrics timeout. Zero uses the built-in 30 seconds.30no
functions.top_queries.limitMaximum number of query patterns top-queries returns. Zero uses the built-in 500.500no
functions.top_queries.time_window_daysDays of query statistics top-queries covers. Zero uses the built-in 7 days; -1 covers all retained history.7no
functions.deadlock_info.disabledDisable the deadlock-info Function.nono
functions.deadlock_info.timeoutQuery timeout for deadlock-info requests, in seconds, independent of the metrics timeout. Zero uses the built-in 30 seconds.30no
functions.deadlock_info.use_ring_bufferRead deadlock reports from the ring_buffer target of the built-in system_health session instead of its event_file target.nono
functions.error_info.disabledDisable the error-info Function.nono
functions.error_info.timeoutQuery timeout for error-info requests, in seconds, independent of the metrics timeout. Zero uses the built-in 30 seconds.30no
functions.error_info.session_nameName of the server-scoped Extended Events session that captures error_reported events.netdata_errorsno
functions.error_info.use_ring_bufferRead error events from the session's ring_buffer target instead of its event_file target.nono
dsn

The URL form covers the common cases:

ScenarioDSN
SQL loginsqlserver://netdata_user:password@host:1433
Windows Authentication (Windows only)sqlserver://host:1433, with no username and password
Named instancesqlserver://netdata_user:password@host/INSTANCENAME; the SQL Server Browser service must be reachable
Azure SQL Managed Instance (private endpoint)sqlserver://my-instance.dns-zone.database.windows.net:1433?database=master
Encrypted connection to a trusted certificateappend ?encrypt=true

The password may come from a secret store instead of the file, for example ${env:MSSQL_PASSWORD}. Percent-encode reserved characters in a literal password (@ as %40).

collect_disabled_jobs

Each disabled job then gets the same four execution charts as an enabled one: last execution status, duration, age, and current run time. The stock last-execution alerts still fire only for enabled jobs.

cloud_auth.azure_ad.mode

Required in the configuration file whenever cloud_auth.provider is azure_ad; the configuration form preselects default. The default chain tries environment credentials, a managed identity, and local developer sign-ins in turn, which suits development more than production.

functions.top_queries.limit

The same limit caps the number of rows error-info returns.

functions.top_queries.time_window_days

With Query Store, the window selects the runtime statistics intervals to aggregate. On the plan-cache fallback it keeps only plans executed within the window, because the plan cache has no interval history. Shorter windows make the query cheaper on busy servers.

functions.deadlock_info.use_ring_buffer

The ring buffer is volatile: its contents are lost on restart or failover and its capacity is small, so older deadlocks disappear sooner than from the event files, and parsing it costs more CPU on the server. Applies to SQL Server and Azure SQL Managed Instance. Azure SQL Database has no system_health session, so deadlock-info is unavailable there regardless of this option.

functions.error_info.session_name

Create the session as described under Live Data. When it is missing or its target is unavailable, SQL Server and Managed Instance fall back to the built-in system_health session, which records only selected errors.

functions.error_info.use_ring_buffer

Use it where event files cannot be stored, such as Managed Instance without configured Blob Storage. The session must be running; events are lost on restart or failover, capacity is limited, and XML parsing costs more CPU than reading event files.

via UI

Configure the mssql collector from the Netdata web interface:

  1. Go to Nodes.
  2. Select the node where you want the mssql data-collection job to run and click the (Configure this node). That node will run the data collection.
  3. The Collectors → Jobs view opens by default.
  4. In the Search box, type mssql (or scroll the list) to locate the mssql collector.
  5. Click the + next to the mssql collector to add a new job.
  6. Fill in the job fields, then click Test to verify the configuration and Submit to save.
    • Test runs the job with the provided settings and shows whether data can be collected.
    • If it fails, an error message appears with details (for example, connection refused, timeout, or command execution errors), so you can adjust and retest.

via File

The configuration file name for this integration is go.d/mssql.conf.

The file format is YAML. Generally, the structure is:

update_every: 1
autodetection_retry: 0
jobs:
- name: some_name1
- name: some_name2

You can edit the configuration file using the edit-config script from the Netdata config directory.

cd /etc/netdata 2>/dev/null || cd /opt/netdata/etc/netdata
sudo ./edit-config go.d/mssql.conf
Examples
Basic configuration

A local instance with a SQL login.

Config
jobs:
- name: local
dsn: "sqlserver://netdata_user:password@localhost:1433"

Windows Authentication

A local instance on Windows, signing in as the Netdata service account. Leave the username and password out of the DSN and complete the Grant Windows Authentication access prerequisite.

Config
jobs:
- name: local
dsn: "sqlserver://localhost:1433"

Named instance

A named instance, resolved through the SQL Server Browser service.

Config
jobs:
- name: named_instance
dsn: "sqlserver://netdata_user:password@localhost/INSTANCENAME"

Remote server

An instance on another host, reachable on TCP port 1433.

Config
jobs:
- name: remote
dsn: "sqlserver://netdata_user:password@192.168.1.100:1433"

Azure SQL Managed Instance with a service principal

A managed instance, authenticated with a Microsoft Entra app registration through its private endpoint. Replace the hostname with the managed instance's fully qualified domain name.

Config
jobs:
- name: azure_sql_sp
dsn: "sqlserver://my-instance.dns-zone.database.windows.net:1433?database=master"
cloud_auth:
provider: azure_ad
azure_ad:
mode: service_principal
mode_service_principal:
tenant_id: "00000000-0000-0000-0000-000000000000"
client_id: "11111111-1111-1111-1111-111111111111"
client_secret: "${env:AZURE_CLIENT_SECRET}"

Azure SQL Managed Instance with a managed identity

Netdata runs on an Azure resource and signs in with its system-assigned managed identity. Set mode_managed_identity.client_id to use a user-assigned identity instead.

Config
jobs:
- name: azure_sql_mi
dsn: "sqlserver://my-instance.dns-zone.database.windows.net:1433?database=master"
cloud_auth:
provider: azure_ad
azure_ad:
mode: managed_identity

Multi-instance

Note: When you define multiple jobs, their names must be unique.

Several instances monitored by one Agent.

Config
jobs:
- name: production
dsn: "sqlserver://netdata_user:password@prod-sql:1433"

- name: development
dsn: "sqlserver://netdata_user:password@dev-sql:1433"

Metrics only, no Functions

The Functions return raw query text, which can contain personal or business data. Disable them where the dashboard audience must not see it.

Config
jobs:
- name: local
dsn: "sqlserver://netdata_user:password@localhost:1433"
functions:
top_queries:
disabled: yes
deadlock_info:
disabled: yes
error_info:
disabled: yes

Custom Extended Events session for error-info

The error capture session was created under a name other than netdata_errors, with a ring_buffer target.

Config
jobs:
- name: local
dsn: "sqlserver://netdata_user:password@localhost:1433"
functions:
error_info:
session_name: app_errors
use_ring_buffer: yes

Alerts

The following alerts are available:

Alert nameOn metricDescription
mssql_database_log_percent_used mssql.database_log_percent_usedSQL Server transaction log percent used has been above 90% for the last 15 minutes
mssql_sql_agent_job_last_execution_warning mssql.job_last_execution_statusEnabled SQL Server Agent job succeeded, but at least one step failed in the last completed execution
mssql_sql_agent_job_last_execution_failed mssql.job_last_execution_statusEnabled SQL Server Agent job failed in the last completed execution

Metrics

Metrics grouped by scope.

The scope defines the instance that the metric belongs to. An instance is uniquely identified by a set of labels.

Charts for SQL Server Agent jobs, replication and Always On appear only where the feature exists and the monitoring login can read it; the Overview lists the grant each one needs.

Per Microsoft SQL Server instance

The whole SQL Server instance.

This scope has no labels.

Metrics:

MetricDescriptionDimensionsUnitSQL ServerAzure SQL Managed Instance
mssql.user_connectionsUser connectionsuserconnections
mssql.session_connectionsSession connectionsuser, internalconnections
mssql.blocked_processesBlocked processesblockedprocesses
mssql.batch_requestsBatch requestsbatchrequests/s
mssql.compilationsSQL compilationscompilationscompilations/s
mssql.recompilationsSQL re-compilationsrecompilationsrecompilations/s
mssql.auto_param_attemptsAuto-parameterization attemptstotal, safe, failedattempts/s
mssql.sql_errorsSQL errorserrorserrors/s
mssql.buffer_cache_hit_ratioBuffer cache hit ratiohit_ratiopercentage
mssql.buffer_page_life_expectancyBuffer page life expectancylife_expectancyseconds
mssql.buffer_page_iopsBuffer page I/Oread, writtenpages/s
mssql.buffer_checkpoint_pagesBuffer checkpoint pages flushedflushedpages/s
mssql.buffer_page_lookupsBuffer page lookupslookupslookups/s
mssql.buffer_lazy_writesBuffer lazy writeslazy_writeswrites/s
mssql.memory_totalTotal server memorymemorybytes
mssql.memory_connectionConnection memorymemorybytes
mssql.memory_pending_grantsPending memory grantspendingprocesses
mssql.memory_external_benefitExternal benefit of memorybenefitbenefit
mssql.page_splitsPage splitspagesplits/s
mssql.process_memory_residentProcess resident memory (working set)residentbytes
mssql.process_memory_virtualProcess virtual memory committedvirtualbytes
mssql.process_memory_utilizationProcess memory utilizationutilizationpercentage
mssql.process_page_faultsProcess page faultspage_faultsfaults
mssql.os_memoryOS physical memoryused, availablebytes
mssql.os_pagefileOS page fileused, availablebytes

Per database

One database on the instance.

Labels:

LabelDescription
databaseDatabase name

Metrics:

MetricDescriptionDimensionsUnitSQL ServerAzure SQL Managed Instance
mssql.database_active_transactionsActive transactionsactivetransactions
mssql.database_transactionsTransactionstransactionstransactions/s
mssql.database_write_transactionsWrite transactionswritetransactions/s
mssql.database_log_flushesLog flushesflushesflushes/s
mssql.database_log_flushedLog bytes flushedflushedbytes/s
mssql.database_log_growthsDatabase log growthsgrowthsgrowths
mssql.database_log_file_sizeTransaction log file sizeused, freebytes
mssql.database_log_percent_usedTransaction log space utilizationusedpercentage
mssql.database_log_truncations_shrinksTransaction log truncations and shrinkstruncations, shrinksevents/s
mssql.database_io_stallDatabase I/O stall timeread, writems
mssql.database_data_file_sizeData file sizesizebytes
mssql.database_backup_restore_throughputBackup/Restore throughputthroughputbytes/s
mssql.database_stateDatabase stateonline, restoring, recovering, pending, suspect, emergency, offlinestate
mssql.database_read_onlyDatabase read-only statusread_only, read_writestatus

Per lock stats

One lock resource type, as reported by the Locks performance counters.

Labels:

LabelDescription
resourceLock resource type (Database, File, Object, Page, Key, Extent, RID, HoBT, etc.)

Metrics:

MetricDescriptionDimensionsUnitSQL ServerAzure SQL Managed Instance
mssql.lock_stats_deadlocksDeadlocks by lock resource typedeadlocksdeadlocks/s
mssql.lock_stats_waitsLock waits by lock resource typewaitswaits/s
mssql.lock_stats_timeoutsLock timeouts by lock resource typetimeoutstimeouts/s
mssql.lock_stats_requestsLock requests by lock resource typerequestsrequests/s

Per lock resource

One lock resource type with locks currently granted or waiting, from sys.dm_tran_locks.

Labels:

LabelDescription
resourceLock resource type (Database, File, Object, Page, Key, etc.)

Metrics:

MetricDescriptionDimensionsUnitSQL ServerAzure SQL Managed Instance
mssql.locks_by_resourceLocks by resource typelockslocks

Per wait type

One wait type observed since the instance started, grouped into a wait category.

Labels:

LabelDescription
wait_typeWait type name
wait_categoryWait category (CPU, Lock, Latch, Buffer IO, etc.)

Metrics:

MetricDescriptionDimensionsUnitSQL ServerAzure SQL Managed Instance
mssql.wait_total_timeTotal wait timedurationms
mssql.wait_resource_timeResource wait timedurationms
mssql.wait_signal_timeSignal wait timedurationms
mssql.wait_max_timeMaximum wait timemax_timems
mssql.wait_countWait countwaitswaits/s

Per job

One SQL Server Agent job. Execution charts exist for enabled jobs, and for disabled jobs only when collect_disabled_jobs is set. Not available on Azure SQL Database.

Labels:

LabelDescription
job_nameJob name

Metrics:

MetricDescriptionDimensionsUnitSQL ServerAzure SQL Managed Instance
mssql.job_statusJob statusenabled, disabledstatus
mssql.job_last_execution_statusJob last execution statusunknown, ok, warning, error, canceledstatus
mssql.job_last_execution_durationJob last execution durationdurationseconds
mssql.job_last_execution_ageJob last execution ageageseconds
mssql.job_current_execution_timeJob current execution timedurationseconds

Per replication

One publication on a distributor instance.

Labels:

LabelDescription
publisher_dbPublisher database name
publicationPublication name

Metrics:

MetricDescriptionDimensionsUnitSQL ServerAzure SQL Managed Instance
mssql.replication_statusReplication statusstarted, succeeded, in_progress, idle, retrying, failedstatus
mssql.replication_warningReplication warningsexpiration, latency, merge_expiration, merge_slow_duration, merge_fast_duration, merge_fast_speed, merge_slow_speedflags
mssql.replication_latencyReplication latencyaverage, best, worstseconds
mssql.replication_subscriptionsReplication subscriptionstotal, agents_runningsubscriptions

Per availability group

One Always On Availability Group the instance takes part in. The threads chart requires SQL Server 2019 or later.

Labels:

LabelDescription
ag_nameAvailability group name

Metrics:

MetricDescriptionDimensionsUnitSQL ServerAzure SQL Managed Instance
mssql.ag_sync_healthAvailability group synchronization healthnot_healthy, partially_healthy, healthystate
mssql.ag_recovery_healthAvailability group recovery healthprimary_online, primary_in_progress, secondary_online, secondary_in_progressstate
mssql.ag_threadsAvailability group threadscapture, redo, parallel_redothreads

Per availability group replica

One replica of an availability group. On a secondary replica the state views describe only the local replica.

Labels:

LabelDescription
ag_nameAvailability group name
replica_serverReplica server name
availability_modeAvailability mode (synchronous_commit or asynchronous_commit)
failover_modeFailover mode (automatic or manual)

Metrics:

MetricDescriptionDimensionsUnitSQL ServerAzure SQL Managed Instance
mssql.ag_replica_roleAvailability group replica roleprimary, secondary, resolving, unknownstate
mssql.ag_replica_connected_stateAvailability group replica connected stateconnected, disconnected, unknownstate
mssql.ag_replica_sync_healthAvailability group replica synchronization healthnot_healthy, partially_healthy, healthystate

Per availability group database replica

One database within an availability group replica; secondary lag requires SQL Server 2016+, and redo rate averages bytes redone over active redo time since SQL Server startup.

Labels:

LabelDescription
ag_nameAvailability group name
replica_serverReplica server name
databaseDatabase name

Metrics:

MetricDescriptionDimensionsUnitSQL ServerAzure SQL Managed Instance
mssql.ag_db_sync_stateAG database synchronization statenot_synchronizing, synchronizing, synchronized, reverting, initializingstate
mssql.ag_db_log_send_queueAG database log send queue sizequeue_sizebytes
mssql.ag_db_log_send_rateAG database log send ratesend_ratebytes/s
mssql.ag_db_redo_queueAG database redo queue sizequeue_sizebytes
mssql.ag_db_redo_rateAG database redo rateredo_ratebytes/s
mssql.ag_db_filestream_send_rateAG database filestream send ratesend_ratebytes/s
mssql.ag_db_secondary_lagAG database secondary laglagseconds
mssql.ag_db_suspendedAG database data movement suspended stateactive, suspendedstate
mssql.ag_db_failover_readinessAG database failover readinessready, not_readystate
mssql.ag_db_joined_stateAG database joined statejoined, not_joinedstate

Per WSFC cluster

The Windows Server Failover Cluster hosting the availability groups.

This scope has no labels.

Metrics:

MetricDescriptionDimensionsUnitSQL ServerAzure SQL Managed Instance
mssql.ag_cluster_quorum_stateWSFC cluster quorum statenormal, forced, unknownstate

Per WSFC cluster member

One node of the failover cluster.

Labels:

LabelDescription
cluster_memberCluster member name

Metrics:

MetricDescriptionDimensionsUnitSQL ServerAzure SQL Managed Instance
mssql.ag_cluster_member_stateWSFC cluster member stateup, downstate
mssql.ag_cluster_member_quorum_votesWSFC cluster member quorum votesvotesvotes

Per AG page repair

One database with automatic page repair events.

Labels:

LabelDescription
databaseDatabase name

Metrics:

MetricDescriptionDimensionsUnitSQL ServerAzure SQL Managed Instance
mssql.ag_page_repairAG automatic page repair eventssuccessful, failedrepairs

Live Data

Three Functions run diagnostic queries on demand from the dashboard's Live tab. They keep the metrics connection available, but share SQL Server CPU, I/O and locks. They return raw query text, so restrict access to people who may see it.

Top Queries

Retrieves aggregated SQL query performance metrics from Microsoft SQL Server, preferring Query Store runtime statistics and falling back to the plan cache.

With Query Store, this function queries sys.query_store_runtime_stats and related views across all databases with Query Store enabled, aggregating execution statistics by query hash. It provides comprehensive timing, I/O, memory, and parallelism metrics.

Query Store was introduced in SQL Server 2016 (13.x). When it is missing or turned off everywhere, the function falls back to sys.dm_exec_query_stats, the plan cache, and the Source column reports which store answered. The plan cache differs in important ways:

  • It only covers plans that are cached right now. Statistics are lost on restart, recompilation, memory pressure, or DBCC FREEPROCCACHE, so they are not query history.
  • Rows are aggregated by query hash across the whole instance, not per database. Database is selected from the cached statements (currently the minimum value), so it is not reliable per-database attribution when the same query hash occurs in multiple databases, and it is empty for ad-hoc or prepared batches that carry no database context.
  • Standard deviation, memory grant, log bytes, and tempdb usage metrics are unavailable on the plan-cache source, so their columns are omitted. Plan-shape columns (hash match joins, merge joins, nested loops, sorts) remain present with empty values.
  • time_window_days filters on last execution time instead of aggregating a period, because the plan cache keeps no interval history.

Use cases:

  • Identify slow or resource-intensive queries consuming excessive CPU time or memory
  • Analyze I/O patterns (logical reads, physical reads, writes) to detect bottlenecks
  • Monitor parallelism (DOP) and tempdb usage for capacity planning

Query text is truncated at 4096 characters. Columns that the active source or SQL Server release does not provide are omitted.

AspectDescription
NameMssql:top-queries
Require Cloudyes
PerformanceOn SQL Server and Azure SQL Managed Instance, Query Store queries span enabled user databases; the plan-cache fallback reads cached statements across the instance.
• Execution time depends on retained Query Store history or qualifying cached statements and their text
• Aggregation and latest-execution selection process the matching input before the default 500-row result limit
• Error attribution also reads the configured Extended Events target or the system_health fallback. On Standard/Enterprise editions, system_health can retain about 1 GB of event files, which are scanned before selecting recent errors
• Functions keep the metrics connection available, but compete for SQL Server CPU, I/O and locks
• Bounded by functions.top_queries.timeout, independent of the metrics timeout
SecurityQuery text may contain unmasked literal values including potentially sensitive data:
• Personal information in WHERE clauses or INSERT values
• Business data and internal identifiers
• Access should be restricted to authorized personnel only
AvailabilityAvailable when:
• The collector has successfully connected
functions.top_queries.disabled is false
• Query Store answers when the engine exposes it (SQL Server 2016 (13.x) and later, or Azure SQL Managed Instance) and it is enabled on at least one user database
• Otherwise the plan cache (sys.dm_exec_query_stats) answers, which requires query_hash, available since SQL Server 2008
• Returns HTTP 403 when required permissions are missing
• Returns HTTP 499 when the caller cancels the request
• Returns HTTP 503 if the collector is still initializing, the function is disabled, or neither Query Store nor the plan cache can answer
• Returns HTTP 500 if the query fails
• Returns HTTP 504 if the query times out

Prerequisites

Grant plan-cache access

Query Store is optional. SQL Server 2008–2014, and newer instances without an enabled Query Store, use the plan cache automatically. Grant the monitoring login the server permission for its version:

-- SQL Server 2008–2019
GRANT VIEW SERVER STATE TO [netdata_user];

-- SQL Server 2022 and later
GRANT VIEW SERVER PERFORMANCE STATE TO [netdata_user];
Enable Query Store for persistent history

On SQL Server 2016 and later, enable Query Store on the databases whose persistent query history you want to inspect. SQL Server and Azure SQL Managed Instance query all enabled user databases. These steps are not required for the plan-cache fallback.

  1. Verify Query Store state:

    -- SQL Server and Azure SQL Managed Instance
    SELECT name, is_query_store_on
    FROM sys.databases
    WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb');

  2. Enable Query Store where it is disabled:

    ALTER DATABASE [YourDatabaseName] SET QUERY_STORE = ON;
  3. Grant the monitoring account the permissions required by your engine:

    Map the login to a database user in every queried user database before granting the database permission.

    -- SQL Server 2022+ and Azure SQL Managed Instance 2022+
    GRANT VIEW SERVER PERFORMANCE STATE TO [netdata_user];
    USE [YourDatabaseName];
    CREATE USER [netdata_user] FOR LOGIN [netdata_user]; -- once per database
    GRANT VIEW DATABASE PERFORMANCE STATE TO [netdata_user];

    -- SQL Server 2016-2019 and corresponding Managed Instance versions
    GRANT VIEW SERVER STATE TO [netdata_user];
    USE [YourDatabaseName];
    CREATE USER [netdata_user] FOR LOGIN [netdata_user]; -- once per database
    GRANT VIEW DATABASE STATE TO [netdata_user];

info
  • Query Store is available in SQL Server 2016+ and Azure SQL Managed Instance
  • Requires ALTER DATABASE permission to enable Query Store
  • Query Store queries exclude system databases (master, tempdb, model, msdb). The plan cache excludes statements identified as belonging to those databases, but can include statements with unknown database context

Parameters

ParameterTypeDescriptionRequiredDefaultOptions
Filter ByselectSelect the primary sort column. The available options depend on your SQL Server version and include metrics like total execution time, number of calls, CPU time, logical I/O, memory grants, and more. Default is Total Time to focus on most resource-intensive queries.yestotalTime

Returns

Aggregated query execution statistics from Query Store runtime views, or from the plan cache when Query Store is unavailable, providing performance analysis across all monitored databases. Each row represents a unique query pattern (normalized query hash) with cumulative metrics across all its executions.

ColumnTypeUnitVisibilityDescription
SourcestringhiddenStatistics store that produced the row: query-store or plan-cache. Hidden while Query Store answers; shown on the plan-cache fallback, where the numbers cover only currently cached plans.
Query HashstringhiddenUnique hash identifier for the normalized query pattern. Queries with identical structure but different literal values share the same digest.
QuerystringThe SQL query text with literal values truncated at 4096 characters. Use this to identify the actual SQL being executed and spot parameterized queries or injection risks.
DatabasestringDatabase name where the query was executed. Essential for multi-database analysis to identify which database is experiencing query load.
CallsintegerTotal number of times this query pattern has been executed. High values indicate frequently run queries that may impact server performance significantly.
Error AttributionstringStatus of error detail attribution for this query. Values: enabled, no_data, not_enabled, not_supported.
Error NumberintegerMost recent error number observed for this query (when error attribution is enabled).
Error StateintegerhiddenSQL Server error state for the most recent error (when error attribution is enabled).
Error MessagestringMost recent error message for this query (when error attribution is enabled).
Hash Match JoinsintegerCount of Hash Match join operators across all stored plans for this query.
Merge JoinsintegerCount of Merge Join operators across all stored plans for this query.
Nested LoopsintegerCount of Nested Loops operators across all stored plans for this query.
SortsintegerCount of Sort operators across all stored plans for this query.
Total TimedurationmillisecondsCumulative execution time across all query executions. This is a key metric for identifying the most resource-intensive queries in terms of total server time consumption.
Avg TimedurationmillisecondsAverage execution time per query run, calculated as weighted average when execution count is greater than zero. Compare with Total Time to determine if individual executions or high frequency drives resource usage.
Last TimedurationmillisecondshiddenExecution time of the most recent execution for this query pattern. Useful for identifying recent performance changes or individual outlier executions.
Min TimedurationmillisecondshiddenMinimum execution time observed. Helps identify variability in query performance and spot potential optimization opportunities for outliers.
Max TimedurationmillisecondshiddenMaximum execution time observed. Large gaps between Min Time and Max Time may indicate performance instability due to parameter sniffing, data skew, or lock contention.
StdDev TimedurationmillisecondshiddenStandard deviation of execution time. High values indicate inconsistent query performance, making capacity planning difficult and suggesting need for query optimization or consistent indexing.
Avg CPUdurationmillisecondsAverage CPU time consumed per query execution. High values indicate CPU-intensive operations that may include complex calculations, string manipulations, or excessive function calls. Available in SQL Server 2016+.
Last CPUdurationmillisecondshiddenCPU time of the most recent execution. Useful for identifying recent changes in query patterns and resource usage.
Min CPUdurationmillisecondshiddenMinimum CPU time observed. Helps identify variability in CPU consumption and spot efficient vs. inefficient query executions.
Max CPUdurationmillisecondshiddenMaximum CPU time observed. Spikes may indicate complex queries, large result sets, or parallelism issues.
StdDev CPUdurationmillisecondshiddenStandard deviation of CPU time. High variability suggests inconsistent performance due to varying data volumes, plan cache hit rates, or changing execution contexts.
Avg Logical ReadsfloatAverage number of logical read operations (8KB pages) per execution. High values indicate queries scanning large amounts of data through indexes or table scans. Monitor for I/O subsystem impact.
Last Logical ReadsintegerhiddenLogical reads from the most recent execution. Useful for identifying immediate query patterns and recent performance changes.
Min Logical ReadsintegerhiddenMinimum logical reads observed. Helps identify data access patterns and spot outliers.
Max Logical ReadsintegerhiddenMaximum logical reads observed. Very high values may indicate full table scans, missing indexes, or inefficient join operations requiring excessive data access.
StdDev Logical ReadsfloathiddenStandard deviation of logical reads. High variability suggests inconsistent access patterns, potentially indicating performance issues with certain queries or data volumes.
Avg Logical WritesfloatAverage number of logical write operations per execution. High values indicate heavy write workloads that may benefit from batching or optimization.
Last Logical WritesintegerhiddenLogical writes from the most recent execution. Helps track recent write activity and identify immediate performance impact.
Min Logical WritesintegerhiddenMinimum logical writes observed. Helps identify read-heavy vs. write-heavy query patterns and data access characteristics.
Max Logical WritesintegerhiddenMaximum logical writes observed. Spikes may indicate bulk insert/update operations, large transactions, or data migration activities.
StdDev Logical WritesfloathiddenStandard deviation of logical writes. High values indicate write performance variability, potentially suggesting inconsistent transaction sizes or periodic bulk operations.
Avg Physical ReadsfloatAverage number of physical read operations from storage per execution. High values indicate queries requiring substantial disk I/O for data retrieval, potentially due to full table scans or missing covering indexes.
Last Physical ReadsintegerhiddenPhysical reads from the most recent execution. Useful for identifying immediate I/O patterns and recent storage subsystem pressure.
Min Physical ReadsintegerhiddenMinimum physical reads observed. Helps baseline I/O patterns and identify read-intensive query scenarios.
Max Physical ReadsintegerhiddenMaximum physical reads observed. Extremely high values may indicate storage subsystem bottlenecks, full table scans without covering indexes, or queries processing very large data volumes.
StdDev Physical ReadsfloathiddenStandard deviation of physical reads. High variability suggests inconsistent disk access patterns, potentially indicating intermittent I/O performance issues or storage contention.
Avg CLR TimedurationmillisecondsAverage CLR (Common Language Runtime) time per execution. High values indicate managed code (stored procedures, functions, triggers) with heavy computations, garbage collection pressure, or inefficient memory allocations. Available in SQL Server 2016+.
Last CLR TimedurationmillisecondshiddenCLR time of the most recent execution. Useful for identifying recent managed code performance changes and detecting inefficient code deployments.
Min CLR TimedurationmillisecondshiddenMinimum CLR time observed. Helps identify efficient managed code executions and spot expensive CLR operations.
Max CLR TimedurationmillisecondshiddenMaximum CLR time observed. Spikes may indicate complex managed code operations, large object allocations, or expensive .NET framework method calls.
StdDev CLR TimedurationmillisecondshiddenStandard deviation of CLR time. High variability suggests inconsistent managed code execution patterns, potentially varying by execution parameters, data volumes, or different code paths being taken.
Avg DOPfloatAverage Degree of Parallelism (DOP) per query. Higher values indicate queries utilizing more CPU cores through parallelism, potentially consuming significant server resources. Values above 1 indicate intra-query parallelism; values of 1 indicate serial execution.
Last DOPintegerhiddenDOP of the most recent execution. Helps track recent parallelism patterns and identify changes in query execution behavior.
Min DOPintegerhiddenMinimum DOP observed. Values of 0 may indicate serial execution; values above 1 suggest parallel query execution within individual queries.
Max DOPintegerhiddenMaximum DOP observed. Very high values (>4) may indicate aggressive parallelism consuming excessive resources and potentially affecting concurrent workloads. Available in SQL Server 2016+.
StdDev DOPfloathiddenStandard deviation of DOP. High variability suggests inconsistent parallelism patterns across executions, potentially indicating performance variability based on data characteristics or query complexity.
Avg Memory (8KB pages)floatAverage memory grant (in 8KB pages) per execution. High values indicate memory-intensive queries that may benefit from index optimization, reduced result sets, or query tuning to reduce working memory usage.
Last Memory (8KB pages)integerhiddenMemory grant from the most recent execution. Useful for identifying recent memory pressure and tracking immediate impact of resource-intensive queries.
Min Memory (8KB pages)integerhiddenMinimum memory grant observed. Helps identify memory-efficient queries and baseline memory requirements for common operations.
Max Memory (8KB pages)integerhiddenMaximum memory grant observed. Spikes may indicate queries with large sort operations, hash joins, temporary table creation, or excessive parameter lengths consuming working memory.
StdDev MemoryfloathiddenStandard deviation of memory grants. High variability suggests inconsistent memory usage patterns, potentially varying by execution parameters, result set sizes, or different code paths being executed.
Avg RowsfloatAverage number of rows processed per query execution. High values indicate queries returning large result sets that may consume significant network bandwidth, memory for result buffers, and client application resources.
Last RowsintegerhiddenRow count from the most recent execution. Helps identify recent query patterns and track immediate data processing requirements.
Min RowsintegerhiddenMinimum rows observed. Helps identify data access patterns and spot outliers in result set sizes.
Max RowsintegerhiddenMaximum rows observed. Extremely high values may indicate full table scans without WHERE clauses, missing or inefficient filters, or data export operations.
StdDev RowsfloathiddenStandard deviation of rows processed. High variability suggests inconsistent result set sizes, potentially due to varying query filters, parameterized inputs, or different data distributions across executions.
Avg Log BytesfloatAverage transaction log bytes written per query execution (SQL Server 2017+). High values indicate write-intensive operations (INSERT/UPDATE/DELETE), large transactions, or bulk modifications. This measures WAL activity, not diagnostic logging.
Last Log BytesintegerhiddenTransaction log bytes from the most recent execution. Useful for tracking recent write activity.
Min Log BytesintegerhiddenMinimum transaction log bytes observed. Helps identify write-efficient queries and baseline requirements.
Max Log BytesintegerhiddenMaximum transaction log bytes observed. Spikes may indicate bulk operations, large transactions, or queries affecting many rows.
StdDev Log BytesfloathiddenStandard deviation of transaction log bytes. High variability suggests inconsistent write patterns, potentially varying by the number of rows affected or transaction sizes.
Avg TempDB (8KB pages)floatAverage tempdb space usage (in 8KB pages) per execution. High values indicate queries that create or use large temporary objects, work tables, sort operations, or have heavy tempdb spillage from disk. High tempdb usage can lead to disk I/O contention and overall performance degradation.
Last TempDB (8KB pages)integerhiddenTempdb space from the most recent execution. Useful for identifying recent tempdb pressure and tracking immediate disk I/O impact of resource-intensive queries.
Min TempDB (8KB pages)integerhiddenMinimum tempdb space observed. Helps identify tempdb-efficient queries and baseline temporary object requirements for common operations.
Max TempDB (8KB pages)integerhiddenMaximum tempdb space observed. Spikes may indicate queries with large sort operations, hash joins, index spool usage, or temporary table creation consuming substantial tempdb space. Can lead to tempdb autogrow and disk space issues.
StdDev TempDBfloathiddenStandard deviation of tempdb space usage. High variability suggests inconsistent temporary object usage patterns, potentially varying by query complexity, parameter types, or different data access patterns affecting temporary object creation.

Deadlock Info

Retrieves the most recent deadlock event from SQL Server's system_health Extended Events session (xml_deadlock_report).

The deadlock graph XML is parsed to attribute the deadlock to the participating processes and their query text, lock mode, lock status, and wait resource.

Use cases:

  • Identify which process was chosen as the deadlock victim
  • Inspect the waiting resource and lock mode involved in the deadlock
  • Correlate deadlocks with recent application changes or deployments

Query text and wait resource strings are truncated at 4096 characters for display purposes.

AspectDescription
NameMssql:deadlock-info
Require Cloudyes
PerformanceExecutes on-demand queries against the selected system_health event_file or ring_buffer target:
• Not part of regular metric collection
• Overhead is limited to function execution time and XML parsing
SecurityQuery text and wait resource strings may include unmasked literal values including sensitive data (PII/secrets):
• SQL literals such as emails, IDs, or tokens
• Schema and table names that may be sensitive in some environments
• Restrict dashboard access to authorized personnel only
AvailabilityAvailable on SQL Server and Azure SQL Managed Instance when:
• The collector has successfully connected
functions.deadlock_info.disabled is false
• SQL Server 2022+ has VIEW SERVER PERFORMANCE STATE; older versions have VIEW SERVER STATE
• Returns HTTP 200 with empty data when no deadlock is found
• Returns HTTP 403 when permission is missing
• Returns HTTP 499 when the caller cancels the request
• Returns HTTP 500 if the query fails or the required ring-buffer target is unavailable
• Returns HTTP 561 when the deadlock graph cannot be parsed
• Returns HTTP 503 if the collector is still initializing or the function is disabled
• Returns HTTP 504 if the query times out

Prerequisites

No additional configuration is required.

Parameters

This function has no parameters.

Returns

Parsed deadlock participants from the latest detected deadlock event. Each row represents one process involved in the deadlock.

ColumnTypeUnitVisibilityDescription
Row IDstringhiddenUnique row identifier composed of deadlock ID and process ID.
Deadlock IDstringIdentifier for the deadlock event, derived from the deadlock timestamp to group participating processes.
TimestamptimestampTimestamp of the deadlock event from Extended Events when available; otherwise the function execution time.
Process IDstringDeadlock graph process identifier for the process involved in the deadlock.
SPIDintegerSQL Server session ID (SPID) for the process when available.
ECIDintegerExecution context ID (ECID) for parallel execution contexts when available.
Victimstring"true" when the process was chosen as the deadlock victim and rolled back; otherwise "false".
QuerystringSQL query text for the process involved in the deadlock. Truncated to 4096 characters.
Lock ModestringLock mode reported for the process within the deadlock graph (for example X or S).
Lock StatusstringLock status for the process. WAITING indicates the process was waiting on a lock.
Wait ResourcestringLock resource identifier from the deadlock graph showing what the process was waiting on.
DatabasestringDatabase name mapped from the deadlock graph database ID when available.

Error Info

Retrieves recent SQL errors from a user-managed Extended Events session that captures sqlserver.error_reported with both the sql_text and query_hash actions.

When the configured session or target is unavailable, the function falls back to the built-in system_health session on SQL Server 2012+. The Source column identifies which source produced each row; system_health captures only selected errors and is not a complete replacement for a dedicated error session.

The session should be created by an administrator and include either an event_file target (the default) or a ring_buffer target when functions.error_info.use_ring_buffer is enabled. If it is unavailable, Netdata uses the built-in system_health target as a reduced-coverage fallback. Netdata returns recent error events with error number, message, and SQL text. The query_hash action is required for reliable mapping into top-queries (query text fallback is best-effort).

Use cases:

  • Identify recent query errors and their messages
  • Correlate errors to query text
  • Validate error rates seen in top-queries
AspectDescription
NameMssql:error-info
Require Cloudyes
PerformanceExecutes on-demand queries against the configured Extended Events target, falling back to system_health when unavailable:
• Also used for error attribution by top-queries, but not by regular metric collection
• event_file reads scan retained files and parse matching errors before returning the newest rows
• On SQL Server, the dedicated-session settings of 6 MB per file and three rollover files keep the conservative filesystem scan envelope near 24 MB (current file plus rollovers)
• The system_health fallback has separate retention settings: Standard/Enterprise editions can retain about 1 GB. A small response limit does not bound the files scanned
• Existing sessions keep their own retention settings; the collector does not alter them
• Keeps the metrics connection available, but shares SQL Server CPU, I/O and locks
SecurityError messages and query text may include unmasked literal values including sensitive data (PII/secrets):
• Restrict dashboard access to authorized personnel only
AvailabilityAvailable on SQL Server 2012+ and Azure SQL Managed Instance when:
• The collector has successfully connected
functions.error_info.disabled is false
• The configured session is used when its selected target is available; otherwise SQL Server/Managed Instance falls back to the built-in system_health target
• When functions.error_info.use_ring_buffer is false, the configured session has an event_file target. Its configured filename is resolved from catalog metadata, so it need not match the session name or be running
• When functions.error_info.use_ring_buffer is true, the configured session is running and has a ring_buffer target
• SQL Server 2022+/Managed Instance 2022+ has VIEW SERVER PERFORMANCE STATE; older SQL Server has VIEW SERVER STATE
• Returns HTTP 200 with empty data when no errors are found
• Returns HTTP 403 when permission is missing
• Returns HTTP 499 when the caller cancels the request
• Returns HTTP 500 if the query fails
• Returns HTTP 503 if neither the selected target nor the applicable system_health fallback is available, or the function is disabled
• Returns HTTP 504 if the query times out

Prerequisites

Create an Extended Events session for error capture

Create an Extended Events session that captures sqlserver.error_reported with sql_text and query_hash actions. Choose the engine scope and target that match your deployment and functions.error_info.use_ring_buffer setting.

SQL Server — event_file (default):

CREATE EVENT SESSION [netdata_errors] ON SERVER
ADD EVENT sqlserver.error_reported(
ACTION(sqlserver.sql_text, sqlserver.query_hash)
)
ADD TARGET package0.event_file(
SET filename=N'netdata_errors',
max_file_size=6,
max_rollover_files=3
);
GO

ALTER EVENT SESSION [netdata_errors] ON SERVER STATE = START;
GO

Netdata resolves the configured filename from catalog metadata and can read retained event files after the session stops. The 6 MB file size and three rollover files preserve recent history while bounding the amount of retained XML that one request must scan. These settings affect only a session created from this example; Netdata does not modify existing sessions.

SQL Server and Azure SQL Managed Instance — ring_buffer:

CREATE EVENT SESSION [netdata_errors] ON SERVER
ADD EVENT sqlserver.error_reported(
ACTION(sqlserver.sql_text, sqlserver.query_hash)
)
ADD TARGET package0.ring_buffer
WITH (STARTUP_STATE = ON);
GO

ALTER EVENT SESSION [netdata_errors] ON SERVER STATE = START;
GO

Set functions.error_info.use_ring_buffer: true. The session starts automatically after restart or failover, but events previously held in memory are lost.

Azure SQL Managed Instance — event_file (default):

Managed Instance requires Azure Blob Storage for event files. Create a server-scoped credential in master and grant the Database Engine access to the storage container first. See Microsoft's event_file setup guide.

CREATE EVENT SESSION [netdata_errors] ON SERVER
ADD EVENT sqlserver.error_reported(
ACTION(sqlserver.sql_text, sqlserver.query_hash)
)
ADD TARGET package0.event_file(
SET filename=N'https://<storage-account>.blob.core.windows.net/<container>/netdata_errors.xel',
max_file_size=6
);
GO

ALTER EVENT SESSION [netdata_errors] ON SERVER STATE = START;
GO

On Managed Instance, max_rollover_files does not currently limit retained blobs. Configure an Azure Storage lifecycle policy to bound retention; max_file_size alone does not bound the total data scanned. Alternatively, use the server-scoped ring buffer example above.

-- SQL Server 2022+ and Azure SQL Managed Instance 2022+
GRANT VIEW SERVER PERFORMANCE STATE TO [netdata_user];

-- SQL Server 2019 and earlier
GRANT VIEW SERVER STATE TO [netdata_user];

If you use a different session name, set it in the collector config:

jobs:
- name: local
dsn: "sqlserver://user:pass@localhost:1433"
functions:
error_info:
session_name: your_session_name

Parameters

This function has no parameters.

Returns

Recent error events from the configured Extended Events session or the system_health fallback.

ColumnTypeUnitVisibilityDescription
SourcestringEvent source: configured-session or system-health. The system-health fallback contains only selected errors.
TimestamptimestampTimestamp of the error event.
Error NumberintegerSQL Server error number.
Error StateintegerSQL Server error state.
Error MessagestringError message text.
QuerystringSQL text captured with the error event.
Query HashstringhiddenQuery hash captured with the error event (used for mapping into top-queries).

Troubleshooting

Diagnostics

Debug Mode

Important: Debug mode is not supported for data collection jobs created via the UI using the Dyncfg feature.

To troubleshoot issues with the mssql collector, run the go.d.plugin with the debug option enabled. The output should give you clues as to why the collector isn't working.

  • Navigate to the plugins.d directory, usually at /usr/libexec/netdata/plugins.d/. If that's not the case on your system, open netdata.conf and look for the plugins setting under [directories].

    cd /usr/libexec/netdata/plugins.d/
  • Switch to the netdata user.

    sudo -u netdata -s
  • Run the go.d.plugin to debug the collector:

    ./go.d.plugin -d -m mssql

    To debug a specific job:

    ./go.d.plugin -d -m mssql -j jobName

Getting Logs

If you're encountering problems with the mssql collector, follow these steps to retrieve logs and identify potential issues:

  • Run the command specific to your system (systemd, non-systemd, or Docker container).
  • Examine the output for any warnings or error messages that might indicate issues. These messages should provide clues about the root cause of the problem.
System with systemd

Use the following command to view logs generated since the last Netdata service restart:

journalctl _SYSTEMD_INVOCATION_ID="$(systemctl show --value --property=InvocationID netdata)" --namespace=netdata --grep mssql
System without systemd

Locate the collector log file, typically at /var/log/netdata/collector.log, and use grep to filter for collector's name:

grep mssql /var/log/netdata/collector.log

Note: This method shows logs from all restarts. Focus on the latest entries for troubleshooting current issues.

Docker Container

If your Netdata runs in a Docker container named "netdata" (replace if different), use this command:

docker logs netdata 2>&1 | grep mssql

Known Errors

check failed: error pinging database: unable to open tcp connection with host 'localhost:1433': dial tcp [::1]:1433: connect: connection refused

When

At job start, before any metric is collected. The message ends with the address the driver dialed.

Cause

Nothing accepts TCP connections at the address and port in dsn. SQL Server may have the TCP/IP protocol disabled, listen on another port, or sit behind a firewall that blocks port 1433.

Fix

Enable TCP/IP in SQL Server Configuration Manager and restart the instance, or point dsn at the port the instance uses. Find it from a working session with:

SELECT local_tcp_port FROM sys.dm_exec_connections WHERE session_id = @@SPID;

check failed: error pinging database: no instance matching 'INSTANCENAME' returned from host 'localhost'

When

The DSN names an instance (host/INSTANCENAME) instead of a port.

Cause

Named instances are resolved through the SQL Server Browser service on UDP port 1434. The service is stopped, the port is blocked, or no instance of that name exists on the host.

Fix

Check the instance name, start the SQL Server Browser service, or give the instance a static TCP port and use host:port in dsn.

check failed: error pinging database: mssql: Login failed for user 'netdata_user'. (18456)

Cause

The login or password in dsn is wrong, the login does not exist on this instance, or the instance accepts Windows Authentication only and rejects every SQL login.

Fix

Check the credentials and that the login exists. For SQL logins, switch the instance to "SQL Server and Windows Authentication mode" (Server Properties, Security) and restart it. The SQL Server error log records the reason for every failed login.

check failed: error pinging database: mssql: Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'. (18456)

When

Windows Authentication (no credentials in dsn) against an instance on another machine.

Cause

The Netdata service runs as Local System on a machine that is not in the instance's domain, so it cannot present a Windows identity over the network.

Fix

Join the Netdata host to the domain and grant its computer account as described under Prerequisites, run the Netdata service as a domain account with a SQL Server login, or use a SQL login in dsn.

check failed: batch requests query failed: mssql: VIEW SERVER PERFORMANCE STATE permission was denied on object 'server', database 'master'. (300)

When

At job start, right after the connection succeeded. A second line, mssql: The user does not have permission to perform this action. (297), follows. SQL Server 2019 and earlier name VIEW SERVER STATE instead.

Cause

The login lacks VIEW SERVER STATE, so the first performance counter query is rejected and the job does not start.

Fix

GRANT VIEW SERVER STATE TO netdata_user;

On SQL Server 2022 and later, GRANT VIEW SERVER PERFORMANCE STATE is enough for the metrics.

SQL Server Agent jobs query failed; job metrics will be unavailable: mssql: The SELECT permission was denied on the object 'sysjobs', database 'msdb', schema 'dbo'. (229)

Cause

The login has no access to the SQL Server Agent tables in msdb. Every other metric keeps being collected; the message is logged once.

Fix

USE msdb;
CREATE USER netdata_user FOR LOGIN netdata_user;
GRANT SELECT ON dbo.sysjobs TO netdata_user;
GRANT SELECT ON dbo.sysjobhistory TO netdata_user;
GRANT SELECT ON dbo.sysjobactivity TO netdata_user;

Some SQL Server Agent jobs have only a status chart, or no charts at all

Cause

Disabled jobs get execution charts only when collect_disabled_jobs is set. On Express there is no SQL Server Agent, so no job charts exist at all. Missing SELECT on msdb.dbo.sysjobhistory or msdb.dbo.sysjobactivity removes the execution charts for every job.

Fix

Set collect_disabled_jobs: yes for disabled jobs, or grant the two missing msdb permissions.

No Always On Availability Group charts appear although Always On is enabled

Cause

The availability group catalog views return rows only to logins with VIEW ANY DEFINITION; without it the queries succeed with no rows and nothing is logged. The same grant feeds the data file size and I/O stall charts through sys.master_files, so those exist but stay empty.

Fix

GRANT VIEW ANY DEFINITION TO netdata_user;

top-queries requires VIEW SERVER STATE for the plan cache, or VIEW DATABASE STATE in every queried user database for Query Store

When

Opening top-queries in the dashboard; the response is HTTP 403. On SQL Server 2022 and later the message names VIEW SERVER PERFORMANCE STATE and VIEW DATABASE PERFORMANCE STATE.

Cause

The login can collect metrics but lacks the permission the query statistics source needs: Query Store is read per database, the plan cache at server level.

Fix

Grant the permission the message names, following the top-queries prerequisites under Live Data. For Query Store, the login needs a user and the database-level grant in every user database it should cover.

deadlock-info requires VIEW SERVER STATE permission. Grant with: GRANT VIEW SERVER STATE TO [netdata_user];

When

Opening deadlock-info in the dashboard; the response is HTTP 403. On SQL Server 2022 and later the message names VIEW SERVER PERFORMANCE STATE.

Cause

Reading the system_health Extended Events session needs the server-level state permission the message names.

Fix

Run the GRANT statement from the message as an administrator.

error-info requires VIEW SERVER STATE permission. Grant with: GRANT VIEW SERVER STATE TO [netdata_user];

When

Opening error-info in the dashboard; the response is HTTP 403. The message names VIEW SERVER PERFORMANCE STATE on SQL Server 2022 and later.

Cause

Reading the Extended Events session target needs the state permission the message names, at the scope of the session.

Fix

Run the GRANT statement from the message as an administrator.

error-info not enabled: Extended Events session not found or event_file target missing

When

Opening error-info in the dashboard; the response is HTTP 503. With functions.error_info.use_ring_buffer set, the message ends in ring_buffer target missing.

Cause

No Extended Events session named by functions.error_info.session_name exists with the expected target, and no system_health fallback is available.

Fix

Create the session as described in the error-info prerequisites under Live Data, or set functions.error_info.session_name to the name of an existing session and functions.error_info.use_ring_buffer to match its target.

top_queries query timed out; Function timeout is 30s (functions.top_queries.timeout), but the request deadline may be shorter

When

Any Function; the response is HTTP 504 and the message names the Function and its timeout option.

Cause

The diagnostic query did not finish within functions.<name>.timeout: a large Query Store history, a big plan cache, or gigabytes of system_health event files to scan.

Fix

Raise functions.<name>.timeout, and for top-queries lower functions.top_queries.time_window_days or functions.top_queries.limit. For error-info, create the dedicated session from the prerequisites so the read stays within its small rollover files instead of the system_health history.


Do you have any feedback for this page? If so, you can open a new issue on our netdata/learn repository.