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:

  1. On the dashboard, navigate to the panel you want to update.

  2. Click any part of the panel and then click Configure in the edit pane.

    Panel edit mode opens.

  3. In the Query tab, locate your query expression.

  4. Reference your variable using the syntax $variableName or ${variableName}.

    For example, change up{environment="production"} to up{environment="$environment"}.

    For multi-value variables, use regular expression syntax to match multiple selections:

    For example, use up{environment=~"$environment"} to support selecting multiple environments.

  5. Click Refresh to test the query with the current variable value.

  6. Verify the query returns filtered results based on the variable selection.

  7. Click Save.

  8. (Optional) Enter a description of the changes you’ve made.

  9. Click Save and Back to dashboard.

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. Following are some examples.

Prometheus queries

  • Single value: metric_name{label="$variable"}
  • Multi-value: metric_name{label=~"$variable"}
  • All values: 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.

Were you successful?

Troubleshooting options

Explore the following troubleshooting topic if you need help:

page 5 of 9