Grafana : Conditional Update of custom variable

Hi ,

I have a custom variable “x” … Now based on the value of some other variable ( y) , I would like the populate “x” …E.g if “y” == 1 , then x = 0

And if “y” == 0 , then x = null;

Is such conditional logic possible in Grafana ?

No Grafana does not allow direct if-else logic between variables in the variable settings.
But we can use a workaround using a query variable with PostgreSQL.
You can you this approch mention in steps

Step 1: Create variable y

Step 2: Create variable x

  • Type: Query
  • Name: x
  • Data source: PostgreSQL
  • Query:
SELECT CASE
         WHEN '${y}'::int = 1 THEN '0'
         WHEN '${y}'::int = 0 THEN NULL
       END AS x;

This will make x return:

  • 0 when y = 1

  • null when y = 0

  • Type: Custom

  • Name: y

  • Values: 1,0

  • This will create a dropdown so you can choose between 1 or 0

How to use x

In your panel queries, just use ${x} like this:

SELECT *
FROM my_table
WHERE some_column = ${x}
1 Like

You could do a trick with custom values using infinity csv key values

y would be represented simply as

1
0

x would be represented as

__value,__text
1,0
0,null

then you use filtering mechanism, when y changes update x based on the value of y that matches __value column of variable x

in this case __value represents the value of y so you are creating a relationship