Prometheus query examples are expressions written in PromQL (Prometheus Query Language) that let you extract, aggregate, and analyze time-series data collected by Prometheus. The most basic example is http_requests_total, which returns the current value of that metric for every series that has it; adding a selector like http_requests_total{status="500"} filters to only 500 responses. This article walks through real PromQL examples from simple to advanced, explains how the language works, and answers common questions about writing effective queries.
What Is PromQL and How Does It Differ from SQL?
PromQL is a functional query language designed specifically for time-series data. Unlike SQL, which operates on rows in tables, PromQL operates on streams of (timestamp, value) pairs called series. Each series is uniquely identified by a metric name and a set of label-value pairs (e.g., job="api", instance="10.0.0.1:9090"). PromQL queries return either an instant vector (a single value per series at a given timestamp) or a range vector (multiple values per series over a time window). SQL has no native concept of time ranges; PromQL’s core operations—selectors, rate, increase, and aggregations—are built around time.
Basic Selector Examples
The simplest query is just a metric name: node_cpu_seconds_total. That returns all series for that metric. To narrow down, you use label matchers:
node_cpu_seconds_total{mode="idle"}— only idle CPU secondsnode_cpu_seconds_total{mode!="idle"}— everything except idlehttp_requests_total{status=~"5.."}— regex match for status codes 500-599http_requests_total{status!~"4.."}— exclude 4xx codes
You can combine matchers with commas: node_cpu_seconds_total{cpu="0", mode="user"}. The special label __name__ lets you match metric names: {__name__=~"node_.*"} returns all metrics starting with node_.
Rate, Increase, and Counter Queries
Counters (metrics that only increase, like request counts) need special handling. The raw value is useless because it resets on restart. Use rate() to get per-second average over a window:
rate(http_requests_total[5m])
This gives the average requests per second over the last 5 minutes. For total requests in a window, use increase():
increase(http_requests_total[1h])
For gauges (values that go up and down, like temperature), you don’t use rate. Just query the value directly: node_memory_MemAvailable_bytes. To see the change over time, use delta() for gauges: delta(node_memory_MemFree_bytes[1h]).
Aggregation Examples (sum, avg, max, by, without)
Aggregations collapse multiple series into fewer. The most common is sum():
sum(rate(http_requests_total[5m]))
That sums all request rates across all series into a single number. To keep some labels, use by:
sum by (job) (rate(http_requests_total[5m]))
This gives one result per job. The without clause is the opposite—it removes specified labels and keeps the rest. Other aggregators: avg(), max(), min(), count(), topk(), quantile(). Example: topk(3, max by (instance) (node_cpu_seconds_total)) returns the top 3 instances by CPU seconds.
Binary Operators and Comparisons
You can combine two queries with arithmetic operators (+, -, *, /, %) and comparison operators (==, !=, >, <, >=, <=). For example, to get memory usage percentage:
100 * (1 - node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes)
Comparison operators return 1 if true, 0 if false. So node_load1 > 4 returns 1 for nodes with 1-minute load above 4, and nothing for others. You can use bool modifier to get 0 instead of no result: node_load1 > bool 4.
Vector matching is tricky: when combining two queries, Prometheus matches series by identical label sets. Use on() or ignoring() to control matching. Example: node_memory_MemFree_bytes / ignoring(job) node_memory_MemTotal_bytes ignores the job label when matching.
Common Real-World Query Patterns
Here are practical queries people actually write:
- Error rate percentage:
sum(rate(http_requests_total{status=~"5.."}[5m])) / sum(rate(http_requests_total[5m])) * 100 - CPU utilization per instance:
100 - (avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100) - Disk almost full:
node_filesystem_avail_bytes / node_filesystem_size_bytes < 0.1 - Requests per second per endpoint:
sum by (path) (rate(http_requests_total[1m])) - Memory usage trend:
predict_linear(node_memory_MemFree_bytes[1h], 3600)— predicts value in 1 hour
For alerting, you often wrap queries in max() or min() to avoid duplicate alerts from multiple series.
Time Ranges, Offsets, and Subqueries
Range selectors like [5m] are essential. Valid units: s, m, h, d, w, y. You can offset a query in time: http_requests_total offset 1h returns values from 1 hour ago. This is useful for comparing current vs. previous period: rate(http_requests_total[5m]) / rate(http_requests_total[5m] offset 1d).
Subqueries let you compute a range over an aggregation. Example: max_over_time(sum(rate(http_requests_total[5m]))[1h:]) — this computes the 5-minute rate, sums it, then takes the maximum over the last hour. The syntax is [range:resolution]; the resolution is optional.
Frequently Asked Questions
How do I see the raw values of a metric? Just type the metric name in the Prometheus expression browser and click Execute. You’ll see a table of current values for each series. To see historical values, switch to the Graph tab and set a time range.
Why does my rate() query return no data? Usually because the time window is too small for the scrape interval. If your scrape interval is 15s, using [1m] only gives 4 samples, which is often not enough. Use at least [5m] to get a stable rate. Also, counters that haven’t increased in the window will show no data.
What’s the difference between rate() and irate()? rate() calculates the average per-second increase over the entire window, smoothing out spikes. irate() calculates the instantaneous rate using only the last two samples, which is more volatile and best for short windows (like [5m] in dashboards). For alerting, rate() is usually preferred to avoid false positives.
How do I query a metric that has no labels? That’s fine—just use the metric name. Prometheus will return a single series with no labels. You can still aggregate it: sum(metric_name).
Can I use PromQL to query logs? No. PromQL is only for metrics. Logs are handled by Loki (also from Grafana Labs) which uses LogQL, a different language. They are often used together, but they are separate systems.
Why does my query return multiple values for the same label set? That usually means you have duplicate series due to label mismatches. For example, one metric has instance="localhost:9090" and another has instance="127.0.0.1:9090"—they look similar but are different strings. Use count by (instance) (metric) to find duplicates.
Common Pitfalls and How to Avoid Them
One frequent mistake is using increase() on a gauge—it produces meaningless results because gauges can go down. Another is forgetting that counters reset on restart; rate() handles that automatically, but increase() over a long window may show negative values if a restart occurred. Also, beware of label name typos: Prometheus returns an error if a label doesn’t exist, but if you mistype a label value, you’ll get empty results silently. Always test with a simple selector first. Finally, avoid using sum() without by when you need per-instance values—you’ll collapse everything into one number and lose visibility.
For performance, try to narrow your queries with label matchers before aggregating. Querying sum(rate(http_requests_total[5m])) over a large cluster can be slow; instead, use sum by (job) (rate(http_requests_total{job="api"}[5m])) if you only need one job.
Related
- Who Should Play Achilles? Casting the Mythic Hero
- Achilles Flash Game: History and How to Play
- Present Perfect Wordwall: How Long Does It Take?
How pages are sourced and corrected: Sources and editorial policy.