Use variables in queries
Now that you’ve created variables, you can use them in panel queries to create dynamic filtering. When users change a variable selection, the panel automatically updates to show filtered results based on that selection.
Variables use a basic syntax that works across different data sources. Understanding how to reference variables correctly for your data source ensures your panels respond dynamically to user interactions.
To use variables in panel queries, complete the following steps:
Open a dashboard that already has a variable (for example,
environment) and a panel that queries your metrics data source.If you are not already editing, click Edit in the top-right corner.
Hover over the panel that you want to update, click the panel menu (⋮), then click Edit.
The panel editor opens.
In the Queries tab, update your query to reference the variable with
$variableNameor${variableName}.For example, change
up{environment="production"}toup{environment="$environment"}.For multi-value variables, use regular expression syntax:
up{environment=~"$environment"}.If the label does not exist on your series, the panel shows No data — that confirms the filter is applied. Use a label that exists on your metrics for live filtered results.
Click Run queries (or Refresh) to test the query with the current variable value.
Verify the query returns filtered results based on the variable selection.
Click Save.
Click Back to dashboard to leave the panel editor.
Click Exit edit to leave dashboard edit mode.
When users change the variable selection in the dashboard, Grafana updates the panel data to show filtered results.
Variable syntax examples
Different data sources use different syntax for referencing variables in queries.
Prometheus queries
- Single value:
metric_name{label="$variable"} - Multi-value:
metric_name{label=~"$variable"}
Loki queries
- Single value:
{environment="$environment"} - Multi-value:
{environment=~"$environment"}
SQL queries
- Single value:
SELECT * FROM table WHERE column = '$variable' - Multi-value:
SELECT * FROM table WHERE column IN ($variable:csv)
In the next milestone, you learn how to create dependent variables that cascade based on other variable selections.
Troubleshooting options
Explore the following troubleshooting topic if you need help:
Please tell us what didn't work: