Using MySQL in Grafana

    Grafana ships with a built-in MySQL data source plugin that allows you to query and visualize data from a MySQL compatible database.

    1. Open the side menu by clicking the Grafana icon in the top header.
    2. In the side menu under the Dashboards link you should find a link named Data Sources.
    3. Click the + Add data source button in the top header.
    4. Select MySQL from the Type dropdown.

    Min time interval

    A lower limit for the and $__interval_ms variables. Recommended to be set to write frequency, for example 1m if your data is written every minute. This option can also be overridden/configured in a dashboard panel under data source options. It’s important to note that this value needs to be formatted as a number followed by a valid time identifier, e.g. 1m (1 minute) or 30s (30 seconds). The following time identifiers are supported:

    Database User Permissions (Important!)

    The database user you specify when you add the data source should only be granted SELECT permissions on the specified database and tables you want to query. Grafana does not validate that the query is safe. The query could include any SQL statement. For example, statements like USE otherdb; and DROP TABLE user; would be executed. To protect against this we Highly recommend you create a specific mysql user with restricted permissions.

    Example:

    You can use wildcards (*) in place of database or table if you want to grant access to more databases and tables.

    Query Editor

    Only available in Grafana v5.4+.

    You find the MySQL query editor in the metrics tab in a panel’s edit mode. You enter edit mode by clicking the panel title, then edit.

    The query editor has a link named Generated SQL that shows up after a query has been executed, while in panel edit mode. Click on it and it will expand and show the raw interpolated SQL string that was executed.

    When you enter edit mode for the first time or add a new query Grafana will try to prefill the query builder with the first table that has a timestamp column and a numeric column.

    In the FROM field, Grafana will suggest tables that are in the configured database. To select a table or view in another database that your database user has access to you can manually enter a fully qualified name (database.table) like otherDb.metrics.

    The Time column field refers to the name of the column holding your time values. Selecting a value for the Metric column field is optional. If a value is selected, the Metric column field will be used as the series name.

    The metric column suggestions will only contain columns with a text datatype (text, tinytext, mediumtext, longtext, varchar, char). If you want to use a column with a different datatype as metric column you may enter the column name with a cast: CAST(numericColumn as CHAR). You may also enter arbitrary SQL expressions in the metric column field that evaluate to a text datatype like CONCAT(column1, " ", CAST(numericColumn as CHAR)).

    Columns and Aggregation functions (SELECT)

    In the SELECT row you can specify what columns and functions you want to use. In the column field you may write arbitrary expressions instead of a column name like column1 * column2 / column3.

    If you use aggregate functions you need to group your resultset. The editor will automatically add a GROUP BY time if you add an aggregate function.

    You may add further value columns by clicking the plus button and selecting Column from the menu. Multiple value columns will be plotted as separate series in the graph panel.

    Filter data (WHERE)

    To add a filter click the plus icon to the right of the WHERE condition. You can remove filters by clicking on the filter and selecting Remove. A filter for the current selected timerange is automatically added to new queries.

    To group by time or any other columns click the plus icon at the end of the GROUP BY row. The suggestion dropdown will only show text columns of your currently selected table but you may manually enter any column. You can remove the group by clicking on the item and then selecting Remove.

    If you add any grouping, all selected columns need to have an aggregate function applied. The query builder will automatically add aggregate functions to all columns without aggregate functions when you add groupings.

    Gap Filling

    Grafana can fill in missing values when you group by time. The time function accepts two arguments. The first argument is the time window that you would like to group by, and the second argument is the value you want Grafana to fill missing items with.

    Text Editor Mode (RAW)

    You can switch to the raw query editor mode by clicking the hamburger icon and selecting Switch editor mode or by clicking Edit SQL below the query.

    Macros

    To simplify syntax and to allow for dynamic parts, like date range filters, the query can contain macros.

    We plan to add many more macros. If you have suggestions for what macros you would like to see, please in our GitHub repo.

    If the query option is set to Table then you can basically do any type of SQL query. The table panel will automatically show the results of whatever columns and rows your query returns.

    Query editor with example query:

    The query:

    1. SELECT
    2. title as 'Title',
    3. user.login as 'Created By' ,
    4. dashboard.created as 'Created On'
    5. FROM dashboard
    6. INNER JOIN user on user.id = dashboard.created_by
    7. WHERE $__timeFilter(dashboard.created)

    You can control the name of the Table panel columns by using regular as SQL column selection syntax.

    The resulting table panel:

    Time series queries

    If you set Format as to Time series, then the query must have a column named time that returns either a SQL datetime or any numeric datatype representing Unix epoch in seconds. In addition, result sets of time series queries must be sorted by time for panels to properly visualize the result.

    A time series query result is returned in a . Any column except time or of type string transforms into value fields in the data frame query result. Any string column transforms into field labels in the data frame query result.

    For backward compatibility, there’s an exception to the above rule for queries that return three columns including a string column named metric. Instead of transforming the metric column into field labels, it becomes the field name, and then the series name is formatted as the value of the metric column. See the example with the metric column below.

    You can optionally customize the default series name formatting using instructions in Standard field options/Display name.

    Example with metric column:

    1. SELECT
    2. $__timeGroup(time_date_time,'5m'),
    3. min(value_double),
    4. 'min' as metric
    5. FROM test_data
    6. WHERE $__timeFilter(time_date_time)
    7. GROUP BY time

    Data frame result:

    1. +---------------------+-----------------+
    2. | Name: time | Name: min |
    3. | Labels: | Labels: |
    4. | Type: []time.Time | Type: []float64 |
    5. +---------------------+-----------------+
    6. | 2020-01-02 03:05:00 | 3 |
    7. | 2020-01-02 03:10:00 | 6 |
    8. +---------------------+-----------------+

    Example using the fill parameter in the $__timeGroup macro to convert null values to be zero instead:

    1. SELECT
    2. $__timeGroup(createdAt,'5m',0),
    3. sum(value_double) as value,
    4. hostname
    5. FROM test_data
    6. WHERE
    7. $__timeFilter(createdAt)
    8. GROUP BY time, hostname
    9. ORDER BY time

    Given the data frame result in the following example and using the graph panel, you will get two series named value 10.0.1.1 and value 10.0.1.2. To render the series with a name of 10.0.1.1 and 10.0.1.2 , use a value of ${__field.labels.hostname}.

    Data frame result:

    1. +---------------------+---------------------------+---------------------------+
    2. | Name: time | Name: value | Name: value |
    3. | Labels: | Labels: hostname=10.0.1.1 | Labels: hostname=10.0.1.2 |
    4. | Type: []time.Time | Type: []float64 | Type: []float64 |
    5. +---------------------+---------------------------+---------------------------+
    6. | 2020-01-02 03:05:00 | 3 | 4 |
    7. | 2020-01-02 03:10:00 | 6 | 7 |
    8. +---------------------+---------------------------+---------------------------+

    Example with multiple columns:

    Data frame result:

    1. +---------------------+-----------------+-----------------+
    2. | Name: time | Name: min_value | Name: max_value |
    3. | Labels: | Labels: | Labels: |
    4. | Type: []time.Time | Type: []float64 | Type: []float64 |
    5. +---------------------+-----------------+-----------------+
    6. | 2020-01-02 03:04:00 | 3 | 4 |
    7. | 2020-01-02 03:05:00 | 6 | 7 |
    8. +---------------------+-----------------+-----------------+

    Currently, there is no support for a dynamic group by time based on time range and panel width. This is something we plan to add.

    Templating

    This feature is currently available in the nightly builds and will be included in the 5.0.0 release.

    Instead of hard-coding things like server, application and sensor name in your metric queries you can use variables in their place. Variables are shown as dropdown select boxes at the top of the dashboard. These dropdowns make it easy to change the data being displayed in your dashboard.

    Check out the documentation for an introduction to the templating feature and the different types of template variables.

    Query Variable

    If you add a template variable of the type Query, you can write a MySQL query that can return things like measurement names, key names or key values that are shown as a dropdown select box.

    For example, you can have a variable that contains all values for the hostname column in a table if you specify a query like this in the templating variable Query setting.

    1. SELECT hostname FROM my_host

    A query can return multiple columns and Grafana will automatically create a list from them. For example, the query below will return a list with values from hostname and hostname2.

    1. SELECT my_host.hostname, my_other_host.hostname2 FROM my_host JOIN my_other_host ON my_host.city = my_other_host.city
    1. SELECT event_name FROM event_log WHERE $__timeFilter(time_column)

    Another option is a query that can create a key/value variable. The query should return two columns that are named __text and __value. The __text column value should be unique (if it is not unique then the first value is used). The options in the dropdown will have a text and value that allows you to have a friendly name as text and an id as the value. An example query with hostname as the text and id as the value:

    1. SELECT hostname AS __text, id AS __value FROM my_host

    You can also create nested variables. For example if you had another variable named region. Then you could have the hosts variable only show hosts from the current selected region with a query like this (if region is a multi-value variable then use the comparison operator rather than = to match against multiple values):

    Using __searchFilter to filter results in Query Variable

    Using __searchFilter in the query field will filter the query result based on what the user types in the dropdown select box. When nothing has been entered by the user the default value for __searchFilter is %.

    Important that you surround the __searchFilter expression with quotes as Grafana does not do this for you.

    The example below shows how to use __searchFilter as part of the query field to enable searching for hostname while the user types in the dropdown select box.

    Query

    1. SELECT hostname FROM my_host WHERE hostname LIKE '$__searchFilter'

    From Grafana 4.3.0 to 4.6.0, template variables are always quoted automatically so if it is a string value do not wrap them in quotes in where clauses.

    From Grafana 4.7.0, template variable values are only quoted when the template variable is a multi-value.

    If the variable is a multi-value variable then use the IN comparison operator rather than = to match against multiple values.

    There are two syntaxes:

    $<varname> Example with a template variable named hostname:

    1. SELECT
    2. UNIX_TIMESTAMP(atimestamp) as time,
    3. avarchar as metric
    4. FROM my_table
    5. WHERE $__timeFilter(atimestamp) and hostname in($hostname)
    6. ORDER BY atimestamp ASC

    [[varname]] Example with a template variable named hostname:

    1. SELECT
    2. UNIX_TIMESTAMP(atimestamp) as time,
    3. aint as value,
    4. avarchar as metric
    5. FROM my_table
    6. WHERE $__timeFilter(atimestamp) and hostname in([[hostname]])
    7. ORDER BY atimestamp ASC

    Disabling Quoting for Multi-value Variables

    Grafana automatically creates a quoted, comma-separated string for multi-value variables. For example: if server01 and server02 are selected then it will be formatted as: 'server01', 'server02'. Do disable quoting, use the csv formatting option for variables:

    ${servers:csv}

    Read more about variable formatting options in the Variables documentation.

    Annotations allow you to overlay rich event information on top of graphs. You add annotation queries via the Dashboard menu / Annotations view.

    Example query using time column with epoch values:

    1. SELECT
    2. epoch_time as time,
    3. metric1 as text,
    4. CONCAT(tag1, ',', tag2) as tags
    5. FROM
    6. public.test_data
    7. WHERE
    8. $__unixEpochFilter(epoch_time)

    Example region query using time and timeend columns with epoch values:

    1. SELECT
    2. epoch_time as time,
    3. epoch_timeend as timeend,
    4. metric1 as text,
    5. CONCAT(tag1, ',', tag2) as tags
    6. FROM
    7. public.test_data
    8. WHERE
    9. $__unixEpochFilter(epoch_time)

    Example query using time column of native SQL date/time data type:

    Alerting

    Time series queries should work in alerting conditions. Table formatted queries are not yet supported in alert rule conditions.

    Configure the data source with provisioning

    It’s now possible to configure data sources using config files with Grafana’s provisioning system. You can read more about how it works and all the settings you can set for data sources on the

    Here are some provisioning examples for this data source.

    1. apiVersion: 1
    2. datasources:
    3. - name: MySQL
    4. type: mysql
    5. url: localhost:3306
    6. database: grafana
    7. user: grafana
    8. password: password
    9. jsonData:
    10. maxOpenConns: 0 # Grafana v5.4+
    11. maxIdleConns: 2 # Grafana v5.4+