Count distinct label values with PromQL

Use nested count aggregations to count unique label values, group results by job, and distinguish healthy targets from all known instances.

Best practices
Metrics monitoring and troubleshooting

Use an inner aggregation to produce one result per label value, then count those results:

count(count by (instance) (http_requests_total))

The inner count by (instance) groups the selected series by instance. The outer count returns the number of groups. This counts values represented by the selected series at the query's evaluation time.

Understand the two aggregations

count by (instance) (http_requests_total)

Each result retains its instance label; its numeric value is the number of selected series for that instance. Wrapping it in another count removes that detail and produces the distinct-value count.

If the label is optional, filter out absent or empty values when they should not form a group:

count(count by (instance) (http_requests_total{instance!=""}))

Common variations

Count distinct status codes:

count(count by (status) (http_requests_total{status!=""}))

Count instances separately for each job:

count by (job) (count by (job, instance) (up))

Count successfully scraped target series:

count(up == 1)

The last expression counts selected up series whose value is one. It is not a general distinct-instance count: the same instance value can appear in several jobs. To deduplicate healthy instances, use count(count by (instance) (up == 1)).

Avoid common mistakes

count(http_requests_total) counts time series, not distinct values of a chosen label. Similarly, count_values groups by sample values; it does not directly count a label's unique strings.

These queries reflect an instant evaluation, not every label value seen throughout retention. An empty input may produce an empty result rather than an explicit zero; use or vector(0) only when that display behavior is appropriate.

FAQ

Can I see the values as well as their count? Yes. The inner aggregation retains each value as a result label, which a table can display. For a JSON array of strings, use /api/v1/label/instance/values; Grafana's label-value variable query is another option. label_values() is not a general PromQL function.

Will nested aggregation be fast? It depends on selected series, query scope, and server resources. There is no fixed speed guarantee based only on the number of distinct values. Narrow the selector and inspect query cost on your own data.

Sources

This guide is based on the documentation below; the examples have not been tested against a live deployment.

Get a tailored plan

Contact us

Join the community

Scan with WeChat
to join the community

Try Guance

Start online and pay only for what you use.

Get started

Choose a Guance plan

Code hosting