<!--startmeta
custom_edit_url: "https://github.com/netdata/netdata/edit/master/src/go/plugin/go.d/collector/mysql/integrations/percona_mysql.md"
meta_yaml: "https://github.com/netdata/netdata/edit/master/src/go/plugin/go.d/collector/mysql/metadata.yaml"
sidebar_label: "Percona MySQL"
learn_status: "Published"
learn_rel_path: "Collecting Metrics/Collectors/Databases"
keywords: ['db', 'database', 'mysql', 'maria', 'mariadb', 'sql']
message: "DO NOT EDIT THIS FILE DIRECTLY, IT IS GENERATED BY THE COLLECTOR'S metadata.yaml FILE"
endmeta-->

# Percona MySQL


<img src="https://netdata.cloud/img/percona.svg" width="150"/>


Plugin: go.d.plugin
Module: mysql

<img src="https://img.shields.io/badge/maintained%20by-Netdata-%2300ab44" />

## Overview

This collector monitors the health and performance of MySQL servers and collects general statistics, replication and user metrics.


It connects to the MySQL instance via a TCP or UNIX socket and executes the following commands:

Executed queries:

- `SELECT VERSION();`
- `SHOW GLOBAL STATUS;`
- `SHOW ENGINE INNODB STATUS;`
- `SHOW GLOBAL VARIABLES;`
- `SHOW SLAVE STATUS;` or `SHOW ALL SLAVES STATUS;` (MariaDBv10.2+) or `SHOW REPLICA STATUS;` (MySQL 8.0.22+)
- `SHOW USER_STATISTICS;` (MariaDBv10.1.1+)
- `SELECT TIME,USER FROM INFORMATION_SCHEMA.PROCESSLIST;`


This collector is supported on all platforms.

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


Percona MySQL can be monitored further using the following other integrations:

- [Applications](/src/collectors/apps.plugin/integrations/applications.md)
- [Containers](/src/collectors/cgroups.plugin/integrations/containers.md)

### Default Behavior

#### Auto-Detection

By default, it detects instances running on localhost by trying to connect as root and netdata using known MySQL TCP sockets:

- 127.0.0.1:3306
- "[::1]:3306"


#### Limits

The default configuration for this integration does not impose any limits on data collection.

#### Performance Impact

The default configuration for this integration is not expected to impose a significant performance impact on the system.

## Setup


You can configure the **mysql** collector in two ways:

| Method                | Best for                                                                                 | How to                                                                                                                                 |
|-----------------------|------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------|
| [**UI**](#via-ui)     | Fast setup without editing files                                                         | Go to **Nodes → Configure this node → Collectors → Jobs**, search for **mysql**, then click **+** to add a job. |
| [**File**](#via-file) | If you prefer configuring via file, or need to automate deployments (e.g., with Ansible) | Edit `go.d/mysql.conf` and add a job.                                                                        |

:::important

UI configuration requires paid Netdata Cloud plan.

:::


### Prerequisites

#### Create netdata user

A user account should have the following [permissions](https://dev.mysql.com/doc/refman/8.0/en/privileges-provided.html):

- [`USAGE`](https://dev.mysql.com/doc/refman/8.0/en/privileges-provided.html#priv_usage)
- [`REPLICATION CLIENT`](https://dev.mysql.com/doc/refman/8.0/en/privileges-provided.html#priv_replication-client)
- [`PROCESS`](https://dev.mysql.com/doc/refman/8.0/en/privileges-provided.html#priv_process)

To create the `netdata` user with these permissions, execute the following in the MySQL shell:

- **MySQL and MariaDB < 10.5.9**

  ```mysql
  CREATE USER 'netdata'@'localhost';
  GRANT USAGE, REPLICATION CLIENT, PROCESS ON *.* TO 'netdata'@'localhost';
  FLUSH PRIVILEGES;
  ```

- **MariaDB >= 10.5.9**

  For MariaDB 10.5.9 and later, use the `SLAVE MONITOR` privilege instead of `REPLICATION CLIENT`:

  ```mysql
  CREATE USER 'netdata'@'localhost';
  GRANT USAGE, SLAVE MONITOR, PROCESS ON *.* TO 'netdata'@'localhost';
  FLUSH PRIVILEGES;
  ```

The `netdata` user will have the ability to connect to the MySQL server on localhost without a password.
It will only be able to gather statistics without being able to alter or affect operations in any way.


#### Enable User Statistics (optional)

To collect per-user statistics, the [User Statistics](https://mariadb.com/docs/server/ha-and-performance/optimization-and-tuning/query-optimizations/statistics-for-optimizing-queries/user-statistics) plugin must be enabled.
This is available for **MariaDB** and **Percona**, not for MySQL.

By default, statistics are not collected. To enable the plugin, set the `userstat` system variable.

- **In a configuration file** (persistent, requires restart):

  ```ini
  [mariadb]
  userstat = 1
  ```

- **Dynamically** (takes effect immediately, does not persist across restarts):

  ```mysql
  SET GLOBAL userstat=1;
  ```



### Configuration

#### Options

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


<details open><summary>Config options</summary>



| Group | Option | Description | Default | Required |
|:------|:-----|:------------|:--------|:---------:|
| **Collection** | update_every | Data collection interval (seconds). | 5 | no |
|  | autodetection_retry | Autodetection retry interval (seconds). Set 0 to disable. | 0 | no |
| **Target** | dsn | MySQL server DSN (Data Source Name). See [DSN syntax](https://github.com/go-sql-driver/mysql#dsn-data-source-name). | root@tcp(localhost:3306)/ | yes |
|  | my.cnf | Path to a `my.cnf` file to read connection settings from the `[client]` section. |  | no |
|  | timeout | Query timeout (seconds). | 1 | no |
| **Functions** | functions.top_queries.disabled | Disable the [top-queries](#top-queries) function. | no | no |
|  | functions.top_queries.timeout | Query timeout (seconds). Uses collector timeout if not set. |  | no |
|  | functions.top_queries.limit | Maximum number of queries to return. | 500 | no |
|  | functions.deadlock_info.disabled | Disable the [deadlock-info](#deadlock-info) function. | no | no |
|  | functions.deadlock_info.timeout | Query timeout (seconds). Uses collector timeout if not set. |  | no |
|  | functions.error_info.disabled | Disable the [error-info](#error-info) function. | no | no |
|  | functions.error_info.timeout | Query timeout (seconds). Uses collector timeout if not set. |  | no |
| **Virtual Node** | vnode | Associates this data collection job with a [Virtual Node](https://learn.netdata.cloud/docs/netdata-agent/configuration/organize-systems-metrics-and-alerts#virtual-nodes). |  | no |


</details>


#### via UI

Configure the **mysql** collector from the Netdata web interface:

1. Go to **Nodes**.
2. Select the node **where you want the mysql data-collection job to run** and click the :gear: (**Configure this node**). That node will run the data collection.
3. The **Collectors → Jobs** view opens by default.
4. In the Search box, type _mysql_ (or scroll the list) to locate the **mysql** collector.
5. Click the **+** next to the **mysql** 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/mysql.conf`.

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

```yaml
update_every: 1
autodetection_retry: 0
jobs:
  - name: some_name1
  - name: some_name2
```
You can edit the configuration file using the [`edit-config`](https://github.com/netdata/netdata/blob/master/docs/netdata-agent/configuration/README.md#edit-configuration-files) script from the
Netdata [config directory](https://github.com/netdata/netdata/blob/master/docs/netdata-agent/configuration/README.md#locate-your-config-directory).

```bash
cd /etc/netdata 2>/dev/null || cd /opt/netdata/etc/netdata
sudo ./edit-config go.d/mysql.conf
```

##### Examples

###### TCP socket

An example configuration.

<details open><summary>Config</summary>

```yaml
jobs:
  - name: local
    dsn: netdata@tcp(127.0.0.1:3306)/

```
</details>

###### Unix socket

An example configuration.

<details open><summary>Config</summary>

```yaml
jobs:
  - name: local
    dsn: netdata@unix(/var/lib/mysql/mysql.sock)/

```
</details>

###### Connection with password

An example configuration.

<details open><summary>Config</summary>

```yaml
jobs:
  - name: local
    dsn: netconfig:password@tcp(127.0.0.1:3306)/

```
</details>

###### my.cnf

An example configuration.

<details open><summary>Config</summary>

```yaml
jobs:
  - name: local
    my.cnf: '/etc/my.cnf'

```
</details>

###### Multi-instance

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

Local and remote instances.


<details open><summary>Config</summary>

```yaml
jobs:
  - name: local
    dsn: netdata@tcp(127.0.0.1:3306)/

  - name: remote
    dsn: netconfig:password@tcp(203.0.113.0:3306)/

```
</details>



## Alerts


The following alerts are available:

| Alert name  | On metric | Description |
|:------------|:----------|:------------|
| [ mysql_10s_slow_queries ](https://github.com/netdata/netdata/blob/master/src/health/health.d/mysql.conf) | mysql.queries | number of slow queries in the last 10 seconds |
| [ mysql_10s_table_locks_immediate ](https://github.com/netdata/netdata/blob/master/src/health/health.d/mysql.conf) | mysql.table_locks | number of table immediate locks in the last 10 seconds |
| [ mysql_10s_table_locks_waited ](https://github.com/netdata/netdata/blob/master/src/health/health.d/mysql.conf) | mysql.table_locks | number of table waited locks in the last 10 seconds |
| [ mysql_10s_waited_locks_ratio ](https://github.com/netdata/netdata/blob/master/src/health/health.d/mysql.conf) | mysql.table_locks | ratio of waited table locks over the last 10 seconds |
| [ mysql_connections ](https://github.com/netdata/netdata/blob/master/src/health/health.d/mysql.conf) | mysql.connections_active | client connections utilization |
| [ mysql_replication ](https://github.com/netdata/netdata/blob/master/src/health/health.d/mysql.conf) | mysql.slave_status | replication status (0: stopped, 1: working) |
| [ mysql_replication_lag ](https://github.com/netdata/netdata/blob/master/src/health/health.d/mysql.conf) | mysql.slave_behind | difference between the timestamp of the latest transaction processed by the SQL thread and the timestamp of the same transaction when it was processed on the master |
| [ mysql_galera_cluster_size_max_2m ](https://github.com/netdata/netdata/blob/master/src/health/health.d/mysql.conf) | mysql.galera_cluster_size | maximum galera cluster size in the last 2 minutes starting one minute ago |
| [ mysql_galera_cluster_size ](https://github.com/netdata/netdata/blob/master/src/health/health.d/mysql.conf) | mysql.galera_cluster_size | current galera cluster size, compared to the maximum size in the last 2 minutes |
| [ mysql_galera_cluster_state_warn ](https://github.com/netdata/netdata/blob/master/src/health/health.d/mysql.conf) | mysql.galera_cluster_state | galera node state is either Donor/Desynced or Joined |
| [ mysql_galera_cluster_state_crit ](https://github.com/netdata/netdata/blob/master/src/health/health.d/mysql.conf) | mysql.galera_cluster_state | galera node state is either Undefined or Joining or Error |
| [ mysql_galera_cluster_status ](https://github.com/netdata/netdata/blob/master/src/health/health.d/mysql.conf) | mysql.galera_cluster_status | galera node is part of a nonoperational component. This occurs in cases of multiple membership changes that result in a loss of Quorum or in cases of split-brain situations. |


## 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.



### Per MariaDB instance

These metrics refer to the entire monitored application.

This scope has no labels.

Metrics:

| Metric | Dimensions | Unit | MySQL | MariaDB | Percona |
|:------|:----------|:----|:---:|:---:|:---:|
| mysql.net | in, out | kilobits/s | • | • | • |
| mysql.queries | queries, questions, slow_queries | queries/s | • | • | • |
| mysql.queries_type | select, delete, update, insert, replace | queries/s | • | • | • |
| mysql.handlers | commit, delete, prepare, read_first, read_key, read_next, read_prev, read_rnd, read_rnd_next, rollback, savepoint, savepointrollback, update, write | handlers/s | • | • | • |
| mysql.table_open_cache_overflows | open_cache | overflows/s | • | • | • |
| mysql.table_locks | immediate, waited | locks/s | • | • | • |
| mysql.join_issues | full_join, full_range_join, range, range_check, scan | joins/s | • | • | • |
| mysql.sort_issues | merge_passes, range, scan | issues/s | • | • | • |
| mysql.tmp | disk_tables, files, tables | events/s | • | • | • |
| mysql.connections | all, aborted | connections/s | • | • | • |
| mysql.connections_active | active, limit, max_active | connections | • | • | • |
| mysql.threads | connected, cached, running | threads | • | • | • |
| mysql.threads_created | created | threads/s | • | • | • |
| mysql.thread_cache_misses | misses | misses | • | • | • |
| mysql.innodb_io | read, write | KiB/s | • | • | • |
| mysql.innodb_io_ops | reads, writes, fsyncs | operations/s | • | • | • |
| mysql.innodb_io_pending_ops | reads, writes, fsyncs | operations | • | • | • |
| mysql.innodb_log | waits, write_requests, writes | operations/s | • | • | • |
| mysql.innodb_redo_log_activity | redo_written, checkpointed | B/s | • | • | • |
| mysql.innodb_redo_log_occupancy | occupancy | percentage | • | • | • |
| mysql.innodb_redo_log_checkpoint_age | age | B | • | • | • |
| mysql.innodb_cur_row_lock | current waits | operations | • | • | • |
| mysql.innodb_rows | inserted, read, updated, deleted | operations/s | • | • | • |
| mysql.innodb_buffer_pool_pages | data, dirty, free, misc, total | pages | • | • | • |
| mysql.innodb_buffer_pool_pages_flushed | flush_pages | requests/s | • | • | • |
| mysql.innodb_buffer_pool_bytes | data, dirty | MiB | • | • | • |
| mysql.innodb_buffer_pool_read_ahead | all, evicted | pages/s | • | • | • |
| mysql.innodb_buffer_pool_read_ahead_rnd | read-ahead | operations/s | • | • | • |
| mysql.innodb_buffer_pool_ops | disk_reads, wait_free | operations/s | • | • | • |
| mysql.innodb_os_log | fsyncs, writes | operations | • | • | • |
| mysql.innodb_os_log_fsync_writes | fsyncs | operations/s | • | • | • |
| mysql.innodb_os_log_io | write | KiB/s | • | • | • |
| mysql.innodb_deadlocks | deadlocks | operations/s | • | • | • |
| mysql.files | files | files | • | • | • |
| mysql.files_rate | files | files/s | • | • | • |
| mysql.connection_errors | accept, internal, max, peer_addr, select, tcpwrap | errors/s | • | • | • |
| mysql.opened_tables | tables | tables/s | • | • | • |
| mysql.open_tables | cache, tables | tables | • | • | • |
| mysql.process_list_fetch_query_duration | duration | milliseconds | • | • | • |
| mysql.process_list_queries_count | system, user | queries | • | • | • |
| mysql.process_list_longest_query_duration | duration | seconds | • | • | • |
| mysql.qcache_ops | hits, lowmem_prunes, inserts, not_cached | queries/s | • | • | • |
| mysql.qcache | queries | queries | • | • | • |
| mysql.qcache_freemem | free | MiB | • | • | • |
| mysql.qcache_memblocks | free, total | blocks | • | • | • |
| mysql.galera_writesets | rx, tx | writesets/s | • | • | • |
| mysql.galera_bytes | rx, tx | KiB/s | • | • | • |
| mysql.galera_queue | rx, tx | writesets | • | • | • |
| mysql.galera_conflicts | bf_aborts, cert_fails | transactions | • | • | • |
| mysql.galera_flow_control | paused | ms | • | • | • |
| mysql.galera_cluster_status | primary, non_primary, disconnected | status | • | • | • |
| mysql.galera_cluster_state | undefined, joining, donor, joined, synced, error | state | • | • | • |
| mysql.galera_cluster_size | nodes | nodes | • | • | • |
| mysql.galera_cluster_weight | weight | weight | • | • | • |
| mysql.galera_connected | connected | boolean | • | • | • |
| mysql.galera_ready | ready | boolean | • | • | • |
| mysql.galera_open_transactions | open | transactions | • | • | • |
| mysql.galera_thread_count | threads | threads | • | • | • |
| mysql.key_blocks | unused, used, not_flushed | blocks | • | • | • |
| mysql.key_requests | reads, writes | requests/s | • | • | • |
| mysql.key_disk_ops | reads, writes | operations/s | • | • | • |
| mysql.binlog_cache | disk, all | transactions/s | • | • | • |
| mysql.binlog_stmt_cache | disk, all | statements/s | • | • | • |

### Per connection

These metrics refer to the replication connection.

This scope has no labels.

Metrics:

| Metric | Dimensions | Unit | MySQL | MariaDB | Percona |
|:------|:----------|:----|:---:|:---:|:---:|
| mysql.slave_behind | seconds | seconds | • | • | • |
| mysql.slave_status | sql_running, io_running | boolean | • | • | • |

### Per user

These metrics refer to the MySQL user.

Labels:

| Label      | Description     |
|:-----------|:----------------|
| user | username |

Metrics:

| Metric | Dimensions | Unit | MySQL | MariaDB | Percona |
|:------|:----------|:----|:---:|:---:|:---:|
| mysql.userstats_cpu | used | percentage |   | • | • |
| mysql.userstats_rows | read, sent, updated, inserted, deleted | operations/s |   | • | • |
| mysql.userstats_commands | select, update, other | commands/s |   | • | • |
| mysql.userstats_denied_commands | denied | commands/s |   | • | • |
| mysql.userstats_created_transactions | commit, rollback | transactions/s |   | • | • |
| mysql.userstats_binlog_written | written | B/s |   | • | • |
| mysql.userstats_empty_queries | empty | queries/s |   | • | • |
| mysql.userstats_connections | created | connections/s |   | • | • |
| mysql.userstats_lost_connections | lost | connections/s |   | • | • |
| mysql.userstats_denied_connections | denied | connections/s |   | • | • |



## Live Data

This collector exposes real-time functions for interactive troubleshooting in the Live tab.


### Top Queries

Retrieves aggregated SQL query performance metrics from MySQL [performance_schema.events_statements_summary_by_digest](https://dev.mysql.com/doc/refman/8.4/en/performance-schema-statement-summary-tables.html) table.

This function queries the `events_statements_summary_by_digest` table which contains aggregated statistics for SQL statements grouped by their digest (normalized query pattern). The function dynamically detects available columns based on your MySQL/MariaDB version.

Use cases:
- Identify slow queries that consume the most execution time
- Find frequently executed queries that may benefit from optimization
- Detect queries with high lock time, errors, or table scans

Query text is truncated at 4096 characters for display purposes.


| Aspect | Description |
|:-------|:------------|
| Name | `Mysql:top-queries` |
| Require Cloud | yes |
| Performance | Queries the `events_statements_summary_by_digest` table:<br/>• On busy servers with high query throughput, the digest table can grow large<br/>• Default limit of 500 rows balances usefulness with performance |
| Security | Query text may contain unmasked literal values including potentially sensitive data:<br/>• Personal information in WHERE clauses or INSERT values<br/>• Business data and internal identifiers<br/>• Access should be restricted to authorized personnel only |
| Availability | Available when:<br/>• The collector has successfully connected to MySQL<br/>• Performance Schema is enabled with statement digest collection<br/>• Returns HTTP 503 if collector is still initializing<br/>• Returns HTTP 500 if the query fails<br/>• Returns HTTP 504 if the query times out |

#### Prerequisites

##### Enable performance_schema statement digest collection

Performance Schema must be enabled and statement instrumentation must be configured to collect digest statistics.

1. Check if Performance Schema is enabled:
   ```sql
   SELECT @@performance_schema;
   ```

2. Check statement instrumentation configuration:
   ```sql
   SELECT * FROM performance_schema.setup_consumers
   WHERE NAME LIKE '%statement%';
   ```

3. The following consumer should be enabled:
   - `events_statements_summary_by_digest`

4. Enable statement consumers if needed:
   ```sql
   UPDATE performance_schema.setup_consumers
   SET ENABLED = 'YES'
   WHERE NAME LIKE 'events_statements%';
   ```

   :::info

   - Changes to `setup_consumers` take effect immediately without requiring a server restart.
   - MariaDB also supports the `events_statements_summary_by_digest` table. Exact consumer names may vary by MariaDB version, so checking `setup_consumers` first as shown above is recommended.

   :::

5. Verify digest table contains data:
   ```sql
   SELECT COUNT(*) FROM performance_schema.events_statements_summary_by_digest;
   ```

   Note: Statement digest data is accumulated since server startup or since the table was last truncated. To reset statistics:
   ```sql
   TRUNCATE TABLE performance_schema.events_statements_summary_by_digest;
   ```

   Ensure that statement instruments are enabled in the Performance Schema so that statement digest statistics are collected. Refer to your MySQL or MariaDB version documentation for the appropriate configuration options.


##### Grant SELECT permission on Performance Schema tables

The netdata user must have SELECT permission on Performance Schema tables. The standard collector permissions
(USAGE, REPLICATION CLIENT, PROCESS) do not automatically include Performance Schema access.

1. Grant the required permission:
   ```sql
   GRANT SELECT ON performance_schema.* TO 'netdata'@'localhost';
   FLUSH PRIVILEGES;
   ```

   :::info

   The host part (`'localhost'`) should match how the netdata user connects. If connecting via TCP/IP, you may need `'netdata'@'%'` or a specific IP address instead.

   :::

2. Verify access:
   ```sql
   -- As the netdata user:
   SELECT COUNT(*) FROM performance_schema.events_statements_summary_by_digest;
   ```



#### Parameters

| Parameter | Type | Description | Required | Default | Options |
|:---------|:-----|:------------|:--------:|:--------|:--------|
| Filter By | select | Select the primary sort column. The available options depend on your MySQL/MariaDB version and include metrics like total execution time, number of calls, lock time, errors, rows examined, and more. Defaults to total execution time. | yes | totalTime |  |

#### Returns

Aggregated statement statistics from Performance Schema, grouped by query digest. Each row represents a unique query pattern with cumulative metrics across all executions.

| Column | Type | Unit | Visibility | Description |
|:-------|:-----|:-----|:-----------|:------------|
| Digest | string |  | hidden | Unique hash identifier for the normalized query pattern. Queries with the same structure (different literal values) share the same digest. |
| Query | string |  |  | Normalized SQL query text with literals replaced by placeholders (e.g., '?' for values). Truncated to 4096 characters. |
| Schema | string |  |  | Database schema name where the query was executed. Empty string for queries without a schema context. |
| Calls | integer |  |  | Total number of times this query pattern has been executed since server startup or since the digest table was last truncated. |
| Total Time | duration | milliseconds |  | Cumulative execution time across all executions. High values indicate queries that consume significant server resources. |
| Min Time | duration | milliseconds | hidden | Minimum execution time observed for a single execution. Helps identify variability in query performance. |
| Avg Time | duration | milliseconds |  | Average execution time (total time divided by calls). Use this to compare performance across different query patterns. |
| Max Time | duration | milliseconds | hidden | Maximum execution time observed for a single execution. Large gaps between min and max may indicate performance instability. |
| Lock Time | duration | milliseconds |  | Total time spent waiting for table locks across all executions. High lock time may indicate contention from concurrent transactions. |
| Errors | integer |  |  | Total number of times this query pattern resulted in an error. Non-zero values require investigation into the underlying issue. |
| Warnings | integer |  |  | Total number of times this query pattern generated warnings. Warnings may indicate data type conversions, NULL handling issues, or other non-critical problems. |
| Error Attribution | string |  |  | Status of error detail attribution for this query. Values: enabled (error details available), no_data (no recent error for this digest), not_enabled (statement history consumers disabled), not_supported (required columns unavailable). |
| Error Number | integer |  |  | Most recent error number observed for this query digest (when error attribution is enabled). |
| SQL State | string |  | hidden | SQLSTATE code for the most recent error (when error attribution is enabled). |
| Error Message | string |  |  | Most recent error message for this query digest (when error attribution is enabled). |
| Rows Affected | integer |  |  | Total number of rows modified by INSERT, UPDATE, DELETE, or REPLACE statements. Useful for tracking write workloads. |
| Rows Sent | integer |  |  | Total number of rows returned to the client by SELECT statements. High values may indicate result sets that are too large. |
| Rows Examined | integer |  |  | Total number of rows read during query execution. A high ratio of rows examined to rows sent suggests missing or inefficient indexes. |
| Temp Disk Tables | integer |  |  | Total number of temporary tables created on disk across all executions. Disk-based temporary tables are significantly slower than in-memory tables and may indicate memory pressure or complex operations requiring sorting/grouping. |
| Temp Tables | integer |  |  | Total number of temporary tables created (both in-memory and on-disk). High values suggest frequent sorting, grouping, or DISTINCT operations. |
| Full Joins | integer |  |  | Total number of joins that performed a full table scan without using an index. These are typically very expensive operations that should be optimized. |
| Full Range Joins | integer |  | hidden | Total number of joins that used a range scan on the first table. Less efficient than indexed joins but better than full scans. |
| Select Range | integer |  | hidden | Total number of joins that used a range on the first table for row selection. |
| Select Range Check | integer |  | hidden | Total number of joins that checked each row after scanning for key ranges. Very inefficient operation. |
| Select Scan | integer |  |  | Total number of joins that performed a full scan of the first table. Indicates missing indexes or suboptimal join order. |
| Sort Merge Passes | integer |  | hidden | Total number of merge passes performed during sort operations. More passes indicate larger datasets that exceed sort buffer size. |
| Sort Range | integer |  | hidden | Total number of sorts that used a range scan. |
| Sort Rows | integer |  |  | Total number of rows sorted across all executions. High values indicate frequent sorting operations on large datasets. |
| Sort Scan | integer |  | hidden | Total number of sorts that required a full table scan. |
| No Index Used | integer |  |  | Total number of executions where no index was used for table access. These queries are prime candidates for index optimization. |
| No Good Index Used | integer |  | hidden | Total number of executions where a non-optimal index was used. Indicates that while an index exists, a better one might improve performance. |
| First Seen | string |  | hidden | Timestamp when this query pattern was first observed. Helps identify new queries that may have been introduced by application changes. |
| Last Seen | string |  | hidden | Timestamp when this query pattern was last executed. Can help identify stale queries that are no longer in use. |
| P95 Time | duration | milliseconds |  | 95th percentile execution time. 95% of executions completed within this time. Available in MySQL 8.0+. Useful for understanding typical performance. |
| P99 Time | duration | milliseconds |  | 99th percentile execution time. 99% of executions completed within this time. Available in MySQL 8.0+. Helps identify outlier slow executions. |
| P99.9 Time | duration | milliseconds | hidden | 99.9th percentile execution time. Available in MySQL 8.0+. Identifies extreme outliers in query performance. |
| Sample Query | string |  | hidden | Example of an actual query execution with literal values preserved. Available in MySQL 8.0+. Helpful for understanding the exact queries being executed. |
| Sample Seen | string |  | hidden | Timestamp when the sample query was captured. Available in MySQL 8.0+. |
| Sample Time | duration | milliseconds | hidden | Execution time of the captured sample query. Available in MySQL 8.0+. |
| CPU Time | duration | milliseconds |  | Total CPU time consumed across all executions. Available in MySQL 8.0.28+. Helps identify CPU-intensive queries. |
| Max Controlled Memory | integer |  |  | Maximum memory controlled by the query executor for this query pattern. Available in MySQL 8.0.31+. Helps identify memory-intensive operations. |
| Max Total Memory | integer |  |  | Maximum total memory used by this query pattern including both controlled and uncontrolled allocations. Available in MySQL 8.0.31+. |

### Deadlock Info

Retrieves the latest detected InnoDB deadlock from `SHOW ENGINE INNODB STATUS`.

The output is parsed to attribute the deadlock to the participating transactions and their query text, lock mode, lock status, and wait resource.

Use cases:
- Identify which query was chosen as the deadlock victim
- Inspect the waiting lock resource and lock mode
- Correlate deadlocks with application changes or deployment events

Query text is truncated at 4096 characters for display purposes.


| Aspect | Description |
|:-------|:------------|
| Name | `Mysql:deadlock-info` |
| Require Cloud | yes |
| Performance | Executes `SHOW ENGINE INNODB STATUS` on demand:<br/>• Not part of regular collection<br/>• Query cost depends on server load and the size of the InnoDB status output |
| Security | Query text and wait resource strings may include unmasked literal values including sensitive data (PII/secrets):<br/>• SQL literals such as emails, IDs, or tokens<br/>• Schema and table names that may be sensitive in some environments<br/>• Restrict dashboard access to authorized personnel only |
| Availability | Available when:<br/>• The collector has successfully connected to MySQL<br/>• `deadlock_info_function_enabled` is true<br/>• The account can run `SHOW ENGINE INNODB STATUS` (PROCESS privilege)<br/>• Returns HTTP 200 with empty data when no deadlock is found<br/>• Returns HTTP 403 when PROCESS privilege is missing<br/>• Returns HTTP 500 if the query fails<br/>• Returns HTTP 504 if the query times out<br/>• Returns HTTP 561 when the deadlock section cannot be parsed<br/>• Returns HTTP 503 if the collector is still initializing or the function is disabled |

#### Prerequisites

##### Enable deadlock-info function in Netdata

Set `deadlock_info_function_enabled: true` in the `go.d/mysql.conf` job.


##### Grant PROCESS privilege

The monitoring user must have PROCESS privilege to run `SHOW ENGINE INNODB STATUS`.



#### Parameters

This function has no parameters.

#### Returns

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

| Column | Type | Unit | Visibility | Description |
|:-------|:-----|:-----|:-----------|:------------|
| Row ID | string |  | hidden | Unique row identifier composed of deadlock ID and process ID. |
| Deadlock ID | string |  |  | Identifier for the deadlock event, used to group participating transactions. |
| Timestamp | timestamp |  |  | Timestamp of the deadlock event. Parsed from the deadlock section when available; otherwise the function execution time. |
| Process ID | string |  |  | MySQL thread id of the transaction involved in the deadlock. |
| Connection ID | integer |  |  | Numeric connection identifier when the process id is numeric. |
| ECID | integer |  |  | Execution context id (engine-specific). This is typically null for MySQL and reserved for cross-engine consistency. |
| Victim | string |  |  | "true" when the transaction was chosen as the deadlock victim and rolled back; otherwise "false". |
| Query | string |  |  | SQL query text for the transaction involved in the deadlock. Truncated to 4096 characters. |
| Lock Mode | string |  |  | Lock mode reported for the waiting lock (for example X or S). |
| Lock Status | string |  |  | Lock status for the transaction. WAITING indicates the transaction was waiting on a lock. |
| Wait Resource | string |  |  | Lock resource line from InnoDB status showing what the transaction was waiting on. |
| Database | string |  |  | Database name when it can be inferred. This may be empty or null depending on the deadlock output. |

### Error Info

Retrieves recent SQL errors from Performance Schema statement history tables.

This function reads `performance_schema.events_statements_history_long` when enabled,
otherwise falls back to `performance_schema.events_statements_history`. It reports the
most recent error per query digest, including error number, SQLSTATE, and message.

Use cases:
- Identify recent query errors and their messages
- Correlate errors to query patterns (digest)
- Validate error rates seen in top-queries

Error messages are truncated by Performance Schema (usually 128 characters).


| Aspect | Description |
|:-------|:------------|
| Name | `Mysql:error-info` |
| Require Cloud | yes |
| Performance | Reads Performance Schema statement history tables on demand:<br/>• Not part of regular collection<br/>• Query cost depends on history table size and server load |
| Security | Error messages and query text may include unmasked literals (PII/secrets).<br/>• Restrict dashboard access to authorized personnel only |
| Availability | Available when:<br/>• The collector has successfully connected to MySQL<br/>• `error_info_function_enabled` is true<br/>• Performance Schema statement history consumers are enabled (history and/or history_long)<br/>• Returns HTTP 200 with empty data when no errors are found<br/>• Returns HTTP 503 when required consumers are not enabled or function disabled<br/>• Returns HTTP 500 if the query fails<br/>• Returns HTTP 504 if the query times out |

#### Prerequisites

##### Enable error-info function in Netdata

Set `error_info_function_enabled: true` in the `go.d/mysql.conf` job.


##### Enable statement history consumers

Ensure `events_statements_history` and/or `events_statements_history_long` consumers are enabled.


##### Grant SELECT on Performance Schema

The monitoring user must have SELECT on `performance_schema.*` to read statement history tables.



#### Parameters

This function has no parameters.

#### Returns

Most recent error per query digest from Performance Schema history tables.

| Column | Type | Unit | Visibility | Description |
|:-------|:-----|:-----|:-----------|:------------|
| Digest | string |  | hidden | Unique hash identifier for the normalized query pattern. |
| Query | string |  |  | Normalized query text when available (digest text or SQL text). |
| Schema | string |  |  | Database schema name when available. |
| Error Number | integer |  |  | MySQL error number for the most recent error of this digest. |
| SQL State | string |  |  | SQLSTATE code for the most recent error. |
| Error Message | string |  |  | Error message for the most recent error. |



## Troubleshooting

### 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 `mysql` 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]`.

  ```bash
  cd /usr/libexec/netdata/plugins.d/
  ```

- Switch to the `netdata` user.

  ```bash
  sudo -u netdata -s
  ```

- Run the `go.d.plugin` to debug the collector:

  ```bash
  ./go.d.plugin -d -m mysql
  ```

  To debug a specific job:

  ```bash
  ./go.d.plugin -d -m mysql -j jobName
  ```

### Getting Logs

If you're encountering problems with the `mysql` 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:

```bash
journalctl _SYSTEMD_INVOCATION_ID="$(systemctl show --value --property=InvocationID netdata)" --namespace=netdata --grep mysql
```

#### System without systemd

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

```bash
grep mysql /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:

```bash
docker logs netdata 2>&1 | grep mysql
```


