How to store and reuse parts of queries to simplify their maintenance?

  • What Grafana version and what operating system are you using?
    v10.4.2, Linux

  • What are you trying to achieve?
    Have some sort of Apache SuperSet DataSet concept - store common part of query string and refer to it while building per-chart queries.

  • How are you trying to achieve it?
    I tried to use const/textbox hidden variables and refer to them in query as ${common_part:raw}. Raw format preserves quotes in original query as is.

  • What happened?
    The problem is that variables used in common query are not substituted. This common_part query uses dashboard variables in WHERE clause and I want them to be substituted with their values - it is like to apply “eval” to common_part content.

  • What did you expect to happen?
    Have a format that will apply eval to variable. Or have better native support for sharing common parts of queries.

Is there a way to store query and then refer to it in other queries as a sub-query?

Use additional hidden query (SQL not constant text) where you build desired SQL string, which can be used in panel data queries. PostgreSQL is serious DB, so you have full range of string functions, but I think simple concat is enough to build sql string, e. g. (example, may not be 100% valid sql syntax, just to provide idea how to use CONCATENATE(||) Operator)

SELECT 'WHERE column=\'' || '${var:raw}' || '\' AND 1=1'

use stored procedures that accept params. also leverage the use of views