# Change Grafana query dynamically based on user inputs

**URL:** <https://community.grafana.com/t/change-grafana-query-dynamically-based-on-user-inputs/26416>\
**Category:** General\
**Tags:** mysql\
**Created:** [February 24, 2020, 10:31am UTC](https://community.grafana.com/t/change-grafana-query-dynamically-based-on-user-inputs/26416 "2020-02-24T10:31:41Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![sarath](https://avatars.discourse-cdn.com/v4/letter/s/958977/32.png) [@sarath](https://community.grafana.com/u/sarath)\
**Post date:** [February 24, 2020, 10:31am UTC](https://community.grafana.com/t/change-grafana-query-dynamically-based-on-user-inputs/26416/1 "2020-02-24T10:31:41Z")

</div>

Is there any way to change the grafana query on the basis of value(variable) selected in grafana dropdown.

Assume that there is a dropdown in grafana dashboard which has values query1 and query2.

Note: We have used MySQL as database

If user selects query1 then query to be executed is:

select time, val1  
from temperature  
where temp = 10;

If user selects query2 then query to be executed is:

select time, humid  
from humidity  
where humidity = 50;

---

<div class="post-metadata">

**Author:** ![danielgonzalez](https://sea2.discourse-cdn.com/grafana/user_avatar/community.grafana.com/danielgonzalez/32/7125_2.png) [@danielgonzalez](https://community.grafana.com/u/danielgonzalez)\
**Post date:** [February 24, 2020, 2:48pm UTC](https://community.grafana.com/t/change-grafana-query-dynamically-based-on-user-inputs/26416/2 "2020-02-24T14:48:37Z")

</div>

Hi Sarath, you can do that if you use templating variables.

> **[Variables](https://grafana.com/docs/grafana/latest/reference/templating/)**
>
> Variables Variables allows for more interactive and dynamic dashboards. 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...

If after reading this, you have doubts i can help you!

---

<div class="post-metadata">

**Author:** ![zahrazare313](https://sea2.discourse-cdn.com/grafana/user_avatar/community.grafana.com/zahrazare313/32/37729_2.png) [@zahrazare313](https://community.grafana.com/u/zahrazare313)\
**Post date:** [April 9, 2023, 5:33am UTC](https://community.grafana.com/t/change-grafana-query-dynamically-based-on-user-inputs/26416/3 "2023-04-09T05:33:28Z")

</div>

hi @danielgonzalez ,can you help me, I need exactly the same thing

---

<div class="post-metadata">

**Author:** ![ldrascic](https://avatars.discourse-cdn.com/v4/letter/l/aca169/32.png) [@ldrascic](https://community.grafana.com/u/ldrascic)\
**Post date:** [April 9, 2023, 3:24pm UTC](https://community.grafana.com/t/change-grafana-query-dynamically-based-on-user-inputs/26416/4 "2023-04-09T15:24:34Z")

</div>

Hi @zahrazare313,  
Dynamic queries can be achieved with dashboard variables.

Here are my two queries in InfluxDB (Flux language) for CPU idle usage and memory usage.

&nbsp;

CPU idle:

```auto
from(bucket: "test")
  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
  |> filter(fn: (r) => r["_measurement"] == "cpu")
  |> filter(fn: (r) => r["_field"] == "usage_idle")
  |> filter(fn: (r) => r["cpu"] == "cpu-total")
  |> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)
  |> yield(name: "mean")

```

&nbsp;

Memory usage:

```auto
from(bucket: "test")
  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
  |> filter(fn: (r) => r["_measurement"] == "mem")
  |> filter(fn: (r) => r["_field"] == "used_percent")
  |> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)
  |> yield(name: "mean")

```

&nbsp;

### **Steps for dynamic queries with variables:**

1. Convert queries into one line queries and escape all commas `,` with backslash `\`. All commas in queries must be escaped beacuse comma is used in `Custom variable` to separate different queries (i.e. CPU, MEM). E.g. my queries would become:

CPU:

```auto
from(bucket: "test") |> range(start: v.timeRangeStart\, stop: v.timeRangeStop) |> filter(fn: (r) => r["_measurement"] == "cpu") |> filter(fn: (r) => r["_field"] == "usage_idle") |> filter(fn: (r) => r["cpu"] == "cpu-total") |> aggregateWindow(every: v.windowPeriod\, fn: mean\, createEmpty: false) |> yield(name: "mean")

```

&nbsp;

MEM:

```auto
from(bucket: "test") |> range(start: v.timeRangeStart\, stop: v.timeRangeStop) |> filter(fn: (r) => r["_measurement"] == "mem") |> filter(fn: (r) => r["_field"] == "used_percent") |> aggregateWindow(every: v.windowPeriod\, fn: mean\, createEmpty: false) |> yield(name: "mean")

```

&nbsp;  
2. Add dashboard variable of type `Custom` (Settins ⚙ → Variables → New variable). Under `Custom options` add all one line formated queries (i.e. CPU and MEM) and separate queries with comma `,`. You can also add labels that will show in drop-down instead of raw query e.g. CPU and MEM. So, final query that you should add in `Custom options` would look like:

```auto
CPU : from(bucket: "test") |> range(start: v.timeRangeStart\, stop: v.timeRangeStop) |> filter(fn: (r) => r["_measurement"] == "cpu") |> filter(fn: (r) => r["_field"] == "usage_idle") |> filter(fn: (r) => r["cpu"] == "cpu-total") |> aggregateWindow(every: v.windowPeriod\, fn: mean\, createEmpty: false) |> yield(name: "mean") , MEM : from(bucket: "test") |> range(start: v.timeRangeStart\, stop: v.timeRangeStop) |> filter(fn: (r) => r["_measurement"] == "mem") |> filter(fn: (r) => r["_field"] == "used_percent") |> aggregateWindow(every: v.windowPeriod\, fn: mean\, createEmpty: false) |> yield(name: "mean")

```

 ![Grafana dynamic query with dashboard variable](https://us1.discourse-cdn.com/grafana/original/3X/1/2/12b2c83c7ff700b14a4e0de42714a32ca2080614.png)

1. Create a panel and in Query field add only variable name e.g `${Query}`.  

2. Choose value from dashboard variable that contains query you would like to display. In right panel you can see raw query that is used in left panel:  

&nbsp;  
Tested on:  
Grafana OSS 9.4.7  
InfluxDB OSS 2.7.0  
OS: Alma linux 8

&nbsp;

**Additional info:**

- Useful variable syntax can be found at [Grafana variable syntax](https://grafana.com/docs/grafana/latest/dashboards/variables/variable-syntax/).

- If you found dynamic queries useful please support Grafana feature request that would allow usage of different delimiters, prefixes and suffixes for multi value variables. This would allow even better dynamic queries since you would be able to create queries with multi value variables. Feature request can be found on:

> **[Ability to specify custom format for multi-value variables · grafana grafana...](https://github.com/grafana/grafana/discussions/45971)**
>
> Right now, the raw format option for variable use comma to separate multi-value variables. I propose to add ability to specify the delimiter and prefix, suffix for such variables. For example, to u...

&nbsp;

Best regards,  
ldrascic

---

<div class="post-metadata">

**Author:** ![zahrazare313](https://sea2.discourse-cdn.com/grafana/user_avatar/community.grafana.com/zahrazare313/32/37729_2.png) [@zahrazare313](https://community.grafana.com/u/zahrazare313)\
**Post date:** [April 10, 2023, 9:32am UTC](https://community.grafana.com/t/change-grafana-query-dynamically-based-on-user-inputs/26416/5 "2023-04-10T09:32:12Z")

</div>

hi @ldrascic, Thank you very much for your detailed explanation and for taking the time

---

<div class="post-metadata">

**Author:** ![ebabeshko](https://avatars.discourse-cdn.com/v4/letter/e/9d8465/32.png) [@ebabeshko](https://community.grafana.com/u/ebabeshko)\
**Post date:** [February 19, 2024, 5:39pm UTC](https://community.grafana.com/t/change-grafana-query-dynamically-based-on-user-inputs/26416/6 "2024-02-19T17:39:01Z")

</div>

> [@ldrascic](#):
>
> `CPU : from(bucket: "test") |> range(start: v.timeRangeStart\, stop: v.timeRangeStop) |> filter(fn: (r) => r["_measurement"] == "cpu") |> filter(fn: (r) => r["_field"] == "usage_idle") |> filter(fn: (r) => r["cpu"] == "cpu-total") |> aggregateWindow(every: v.windowPeriod\, fn: mean\, createEmpty: false) |> yield(name: "mean") , MEM : from(bucket: "test") |> range(start: v.timeRangeStart\, stop: v.timeRangeStop) |> filter(fn: (r) => r["_measurement"] == "mem") |> filter(fn: (r) => r["_field"] == "used_percent") |> aggregateWindow(every: v.windowPeriod\, fn: mean\, createEmpty: false) |> yield(name: "mean")`

hi @ldrascic , thank you for your solution. I also use InfluxDB (Flux) and everything works fine until Flux queries include other variables.

For example, I have a variable test\_var:

 ![query](https://us1.discourse-cdn.com/grafana/original/3X/a/a/aa8faf8a14b62ff28bf45826e54909c9883f294f.png)

And I use it in my query so as to parametrize it (variable Query):

`CPU : from(bucket: "test") |> range(start: v.timeRangeStart\, stop: v.timeRangeStop) |> filter(fn: (r) => r["_measurement"] == "cpu") |> filter(fn: (r) => r["_field"] == "usage_idle") |> filter(fn: (r) => r["cpu"] == "cpu-total") |> aggregateWindow(every: v.windowPeriod\, fn: mean\, createEmpty: false) |> yield(name: "mean") , MEM : from(bucket: "test") |> range(start: v.timeRangeStart\, stop: v.timeRangeStop) |> filter(fn: (r) => r["_measurement"] == "mem") |> filter(fn: (r) => r["_field"] == "${test_var}") |> aggregateWindow(every: v.windowPeriod\, fn: mean\, createEmpty: false) |> yield(name: "mean")`

I get the following error:

![error](https://us1.discourse-cdn.com/grafana/original/3X/b/3/b37141910e0507fab072c6e3eb284217d4779a0b.png)

invalid: error @1:180-1:188: undefined identifier test\_var

If I change ${test\_var} to hardcoded value everything is fine.

Is it possible somehow to change Grafana query **with variables** dynamically based on user inputs?

May be it is necessary to escape variables somehow in Flux in this case?

This query  
`from(bucket: "test") |> range(start: v.timeRangeStart\, stop: v.timeRangeStop) |> filter(fn: (r) => r["_measurement"] == "mem") |> filter(fn: (r) => r["_field"] == "${test_var}") |> aggregateWindow(every: v.windowPeriod\, fn: mean\, createEmpty: false) |> yield(name: "mean")`

works fine if I just use it in a panel, but I need it to be selected by user…

Looks like Grafana **doesn’t replace** variable **test\_var** with its value in this case and sends “${test\_var}” to InfluxDB instead of “used\_percent”

I use Grafana 10.2.1

---

<div class="post-metadata">

**Author:** ![olgasacc](https://avatars.discourse-cdn.com/v4/letter/o/839c29/32.png) [@olgasacc](https://community.grafana.com/u/olgasacc)\
**Post date:** [July 4, 2024, 6:59am UTC](https://community.grafana.com/t/change-grafana-query-dynamically-based-on-user-inputs/26416/7 "2024-07-04T06:59:51Z")

</div>

Hi @ebabeshko did you manage to find any solution for solving this issue? I’m facing exactly the same in my PromQL query now. Thanks

@ldrascic do you have any ideas? My problematic query is  
label\_replace(rate(hb\_in\_req\_count{host=~“($Host)”}[1h]), “custom\_legend”, “Metrics ($1)”, “host”, “(.\*)”). When I set it as an option for variable - the “Host” is not being caught from another variable.  
Is it possible to fix?

---

<div class="post-metadata">

**Author:** ![ebabeshko](https://avatars.discourse-cdn.com/v4/letter/e/9d8465/32.png) [@ebabeshko](https://community.grafana.com/u/ebabeshko)\
**Post date:** [July 4, 2024, 8:37am UTC](https://community.grafana.com/t/change-grafana-query-dynamically-based-on-user-inputs/26416/8 "2024-07-04T08:37:11Z")

</div>

> [@olgasacc](#):
>
> Hi @ebabeshko did you manage to find any solution for solving this issue? I’m facing exactly the same in my PromQL query now. Thanks

I had to hardcode values in queries instead of variables. So now user can choose queries, but none of them contains variables. Otherwise it didn’t work out.
