How to selectively run queries based on variable values

Suppose I have a time series panel consisting of several similar queries, each of which renders a single line in the resulting graph. I would like to have a variable corresponding to each of the queries, maybe a “yes” or “no” value, one or zero, whatever. How could I use these variables to selectively turn on or turn off the corresponding query?

You can’t turn on/off queries.

But you can’t be smart and you can use variables to create conditions in your queries, which will cause no result/desired result output. So queries will be executed anyway, they may just return empty result (no data) based on variable value.

what is your data source?

something like this on MSSQL:

image

I have a variable called AvgVSTotal, depending on whether average or total is selected in the variable, two different queries can be run using an if statement…

1 Like

Short answer: “Postgres”

Longer answer: We do something like this:
DROP TABLE IF EXISTS mytable;
CREATE TEMPORARY TABLE mytable(date date, val double precision);
COPY myindex FROM PROGRAM ‘./getme mydata $var1’;
SELECT …

The table created exists only for the lifetime of the chart, Data comes from a company proprietary data base. This postgres instance runs on its own container and has very little other data, so tends to clean itself out despite heavy usage.

This uses the postgres COPY feature along with a program callable from the query inside grafana. As it’s my container, I can put anything I want into the postgres execution path.

I have complete freedom with the postgres COPY command. Not so with SQL itself.

This sort of thing would work nicely if postgres would support it in an ordinary query.

I have a solution where the query fragments come from a table. Problem is that there are a lot of them and the drop down is uncomfortably large. Also the colleagues complain (too hard to understand etc)