Skip to main content

Using Variables in Queries

1. Referencing Variables (${variable})

Reference Description Example
${variable} Basic variable reference in queries SELECT * FROM users WHERE department = '${dept}'
${variable:csv} Comma-separated values for IN clauses WHERE id IN (${userIds:csv})
${variable:text} Text value with quotes '${appName}'
${variable:regex} Regex pattern for filtering WHERE name ~ '${pattern:regex}'

Example: Using Variables in SQL Query

SELECT 
  timestamp,
  metric_value
FROM metrics 
WHERE 
  environment = '${env}' 
  AND metric_name = '${metric}'
  AND timestamp >= '${timeRange:start}'
Note: Variables must be defined in the dashboard's variable settings before they can be referenced.

2. Using Alternative Syntax ([[variable]])

Variable Type Syntax Description Example
Text [[variable]] Simple text variable substitution SELECT * FROM logs WHERE level = "[[logLevel]]"
Query [[variable:query]] Variable derived from a query result SELECT DISTINCT service FROM logs WHERE level = "[[logLevel]]"
Constant [[variable:constant]] Fixed value variable SELECT * FROM logs WHERE service = "[[serviceName]]"
Interval [[variable:interval]] Time interval variable (e.g., for time series) SELECT * FROM metrics WHERE time > now() - [[timeRange]]

Example: Using Query Variables

SELECT DISTINCT service FROM logs WHERE level = "[[logLevel]]"

Example: Using Interval Variables

SELECT * FROM metrics WHERE time > now() - [[timeRange]]

3. Using Multi-Value Format (${variable:pipe})

When a variable is configured to allow multiple values, Grafana supports using the ${variable:pipe} format to handle these values in queries. This format is particularly useful for filtering data across multiple selections.

Format Description Example
${variable:pipe} Expands to a pipe-separated list of selected values app1|app2|app3

Example: Using Multi-Value Variables in SQL Query

SELECT * FROM logs 
WHERE application IN ('${app:pipe}')
Note: The :pipe format is supported in SQL-based data sources like PostgreSQL, MySQL, and ClickHouse. For other data sources, the format might vary (e.g., :csv for CSV output).
Warning: When using :pipe, ensure that the data source supports the pipe-separated format. If not, it may result in a query error or incorrect filtering.

4. Using CSV Format (${variable:csv})

Property Description Example
variable Variable name in CSV format ${myVar:csv}

Example: Using CSV in a Query

SELECT * FROM products WHERE category IN ("${category:csv}")
Note: The :csv modifier converts the variable value into a comma-separated list enclosed in quotes, suitable for SQL IN clauses.

5. Using Regex Format (${variable:regex})

Use the regex format to transform variable values using regular expressions in Grafana queries.

Format Description Example
${variable:regex} Applies a regex to transform the variable value ${job:regex/(.*)/job=$1/}

Example: Regex Transformation

job:regex/(.*)/job=$1/
Note: The regex format supports capturing groups using parentheses. The replacement string can reference captured groups with $1, $2, etc.

6. Using Percent Encode (${variable:percentencode})

The ${variable:percentencode} modifier in Grafana allows you to percent-encode values within a variable, which is particularly useful when incorporating variable values into URLs or query parameters where special characters need to be escaped.

Modifier Description Example
${variable:percentencode} Encodes a variable value using percent-encoding (URL encoding) to make it safe for use in URLs or query strings. https://api.example.com/data?param=${myVar:percentencode}

Example: Using Percent Encode in a URL


https://api.example.com/data?name=${userInput:percentencode}&category=${category:percentencode}
Note: The :percentencode modifier is especially useful when variable values contain spaces, ampersands (&), or other special characters that would otherwise break the URL structure.

7. Using All Option

The all option in Grafana variables allows users to select all values from a variable source at once. This is particularly useful when working with large datasets or when you want to apply a query across all available values without manually selecting each one.

Property Description Example
all When enabled, allows selection of all values in a variable true or false
allValue Value used when all options are selected. If not set, it defaults to $__all ALL_VALUES

Example: Using All Option in a Variable

datasource: "Prometheus"
name: "host"
type: "query"
label: "Host"
multi: true
includeAll: true
allValue: "ALL_HOSTS"
Note: When using the all option, make sure that your queries can handle large result sets efficiently to avoid performance issues.

8. Using Global Variables ($__interval, $__from)

Variable Description Usage
$__interval Auto-calculated interval for the current time range and resolution Used in queries to adjust for dynamic time ranges. Example: rate(metric[ $__interval ])
$__from Start timestamp of the current time range in milliseconds Used to filter data based on a specific start time. Example: WHERE timestamp > $__from
$__to End timestamp of the current time range in milliseconds Used to filter data based on a specific end time. Example: WHERE timestamp < $__to

Example: Using $__interval in PromQL

rate(cpu_usage_percent[ $__interval ])

Example: Using $__from and $__to in SQL

SELECT * FROM metrics WHERE timestamp > $__from AND timestamp < $__to;

9. Chaining Variables in Queries

Chaining variables in Grafana allows you to use the result of one variable as the input for another, enabling dynamic and cascading query logic. This is particularly useful in scenarios where one variable's output depends on another, such as filtering data based on a previous selection.

Variable Type Query Description
region Query label_values(up, region) Lists all available regions from the up metric.
instance Query label_values(up{region="$region"}, instance) Lists instances filtered by the selected region.

Example: Chaining Variables in a Dashboard

1. Create a variable named "region" with query:
   label_values(up, region)

2. Create a second variable named "instance" with query:
   label_values(up{region="$region"}, instance)

3. Use the "instance" variable in a panel query:
   up{instance="$instance"}
Note: The variable $region is substituted with the selected value when querying for instances, enabling dynamic filtering.

Best Practices for Chaining Variables

  • Use $variableName syntax to reference other variables in queries.
  • Ensure that the dependent variable's query is valid for the selected value of the parent variable.
  • Test chained variables in a dashboard to ensure correct filtering and data display.

10. Using Data Source Variable

Property Description Example
datasource The data source to use for the variable datasource: "Prometheus"
name Name of the variable name: "job"
query Query to fetch data for the variable query: "label_values(job)"

Example: Data Source Variable Configuration

{
  "name": "job",
  "label": "Job",
  "datasource": "Prometheus",
  "query": "label_values(job)"
}
Note: The variable will be populated with unique values from the job label in Prometheus.

Was this article helpful?