Search code examples
prometheusgrafanapromql

Prometheus/PromQL/Grafana: Substraction when the right side range vector is potentially non-existent


I have two counter metrics: always_exists and sometimes_exists.

I want to receive a result vector from the substraction always_exists - sometimes_exists, even if the metric sometimes_exists doesn't exist (i.e. the query returns nothing). I'd like the result to be equal to always_exists - 0 in that case. Is this possible?


Solution

  • Try the following query:

    (always_exists - sometimes_exists) or (always_exists unless sometimes_exists)
    

    It uses or and unless operators. See more details on these operators at https://prometheus.io/docs/prometheus/latest/querying/operators/#logical-set-binary-operators

    P.S. The query can be simplified to sum(always_exists, -sometimes_exists) in VictoriaMetrics, since MetricsQL supports multiple arguments in aggregate functions such as sum. (I'm the core developer of VictoriaMetrics)