PromQL Functions Reference
Complete reference of Prometheus Query Language functions organized by category.
Overview
PromQL Functions Reference
Complete reference of Prometheus Query Language functions organized by category.
Aggregation Operators
Aggregation operators combine multiple time series into fewer time series.
Syntax: <operator> [without|by (<label_list>)] (<instant_vector>)
sum
Calculates sum of values across time series.
# Sum all HTTP requests
sum(http_requests_total)
# Sum by job and endpoint
sum by (job, endpoint) (http_requests_total)
# Sum without instance label
sum without (instance) (http_requests_total)
Use for: Totaling metrics across instances, calculating aggregate throughput.
avg
Calculates average of values across time series.
# Average CPU usage across all instances
avg(cpu_usage_percent)
# Average by environment
avg by (environment) (cpu_usage_percent)
Use for: Average resource usage, typical response times.
max / min
Returns maximum or minimum value across time series.
# Maximum memory usage across instances
max(memory_usage_bytes)
# Minimum available disk space by node
min by (node) (disk_available_bytes)
Use for: Peak resource usage, bottleneck identification.
count
Counts the number of time series.
# Count of running instances
count(up == 1)
# Count of instances by version
count by (version) (app_version_info)
Use for: Counting instances, availability calculations.
count_values
Counts time series with the same value.
# Count how many instances have each version
count_values("version", app_version)
Use for: Distribution analysis, version tracking.
topk / bottomk
Returns k largest or smallest time series by value.
# Top 5 endpoints by request count
topk(5, rate(http_requests_total[5m]))
# Bottom 3 instances by available memory
bottomk(3, node_memory_available_bytes)
Use for: Identifying highest/lowest consumers, troubleshooting hotspots.
quantile
Calculates φ-quantile (0 ≤ φ ≤ 1) across dimensions.
# 95th percentile of response times
quantile(0.95, response_time_seconds)
# 50th percentile (median) by service
quantile(0.5, response_time_seconds) by (service)
Use for: Percentile calculations across simple metrics (not histograms).
stddev / stdvar
Calculates standard deviation or variance.
# Standard deviation of response times
stddev(response_time_seconds)
Use for: Measuring variability, detecting anomalies.
Rate and Increase Functions
Functions for working with counter metrics (cumulative values that only increase).
rate
Calculates per-second average rate of increase over a time range.
# Requests per second over last 5 minutes
rate(http_requests_total[5m])
# Bytes sent per second
rate(bytes_sent_total[1m])
How it works:
- Calculates increase between first and last samples in range
- Divides by time elapsed to get per-second rate
- Automatically handles counter resets
- Extrapolates to range boundaries
Best practices:
- Use with counter metrics only (metrics with
_total,_count,_sum, or_bucketsuffix) - Range should be at least 4x the scrape interval
- Minimum range typically
[1m]to[5m] - Returns average rate, smoothing out spikes
When to use: For graphing trends, alerting on sustained rates, calculating throughput.
irate
Calculates instant rate based on the last two data points.
# Instant rate of HTTP requests
irate(http_requests_total[5m])
# Real-time throughput (sensitive to spikes)
irate(bytes_processed_total[2m])
How it works:
- Uses only the last two samples in the range
- Range determines maximum lookback window
- More sensitive to short-term changes than
rate()
Best practices:
- Use with counter metrics only
- Best for ranges of
[2m]to[5m] - More volatile than
rate(), shows spikes - Good for alerting on sudden changes
When to use: For alerting on spike detection, real-time dashboards showing immediate changes.
Rate vs irate:
rate(): Average over time range, smoothirate(): Instant based on last 2 points, volatile- For graphing: use
rate() - For spike alerts: use
irate()
Native Histogram Support (Prometheus 3.3+): irate() and idelta() now work with native histograms, enabling instant rate calculations on histogram data.
# Instant rate on native histogram (Prometheus 3.3+)
irate(http_request_duration_seconds[5m])
increase
Calculates total increase over a time range.
# Total requests in the last hour
increase(http_requests_total[1h])
# Total bytes sent in the last day
increase(bytes_sent_total[24h])
How it works:
- Syntactic sugar for
rate(v) * range_in_seconds - Returns total increase (not per-second)
- Automatically handles counter resets
- Extrapolates to range boundaries
Best practices:
- Use with counter metrics only
- Useful for calculating totals over periods
- Result can be fractional due to extrapolation
When to use: Calculating totals for billing, capacity planning, SLO calculations.
resets
Counts the number of counter resets within a time range.
# Number of times counter reset in last hour
resets(http_requests_total[1h])
When to use: Detecting application restarts, investigating metric inconsistencies.
Time Functions
Functions for extracting time components and working with timestamps.
time
Returns current evaluation timestamp as seconds since Unix epoch.
# Current timestamp
time()
# Time since metric was last seen (in seconds)
time() - max(metric_timestamp)
Use for: Calculating age of data, time-based math.
timestamp
Returns timestamp of each sample in the instant vector.
# Get timestamp of last scrape
timestamp(up)
# Time since last successful backup
time() - timestamp(last_backup_success)
Use for: Checking staleness, calculating time since event.
year / month / day_of_month / day_of_week
Extract time components from Unix timestamp.
# Current year
year()
# Current month (1-12)
month()
# Current day of month (1-31)
day_of_month()
# Current day of week (0=Sunday, 6=Saturday)
day_of_week()
# Extract from specific timestamp
year(timestamp(last_backup))
Use for: Time-based filtering, business hour alerting.
hour / minute
Extract hour (0-23) or minute (0-59) from timestamp.
# Current hour
hour()
# Current minute
minute()
# Check if within business hours (9 AM - 5 PM)
hour() >= 9 and hour() < 17
Use for: Time-of-day alerting, business hour filtering.
days_in_month
Returns number of days in the month of the timestamp.
# Days in current month
days_in_month()
# Days in month of specific timestamp
days_in_month(timestamp(metric))
Use for: Calendar calculations, month-end processing.
Prometheus 3.x Time Functions (Experimental)
These functions are available in Prometheus 3.5+ behind the --enable-feature=promql-experimental-functions flag.
ts_of_max_over_time
Returns the timestamp when the maximum value occurred in the range.
# When did CPU usage peak in the last hour?
ts_of_max_over_time(cpu_usage_percent[1h])
# Find when error spike happened
ts_of_max_over_time(rate(errors_total[5m])[1h:1m])
Use for: Incident investigation, finding when peaks occurred.
ts_of_min_over_time
Returns the timestamp when the minimum value occurred in the range.
# When was memory usage lowest?
ts_of_min_over_time(memory_available_bytes[1h])
# Find when throughput dropped
ts_of_min_over_time(rate(requests_total[5m])[1h:1m])
Use for: Finding performance troughs, capacity planning.
ts_of_last_over_time
Returns the timestamp of the last sample in the range.
# When was this metric last scraped?
ts_of_last_over_time(up[10m])
# Check data freshness
time() - ts_of_last_over_time(metric[1h])
Use for: Detecting stale data, monitoring scrape health.
first_over_time (Prometheus 3.7+)
Returns the first (oldest) value in the time range.
Requires Feature Flag: Must enable with
--enable-feature=promql-experimental-functions
# Get the first value in a range
first_over_time(metric[1h])
# Compare current vs initial value
metric - first_over_time(metric[1h])
# Calculate change over time window
last_over_time(metric[1h]) - first_over_time(metric[1h])
Use for: Baseline comparisons, detecting drift, calculating change over time.
ts_of_first_over_time (Prometheus 3.7+)
Returns the timestamp of the first sample in the range.
Requires Feature Flag: Must enable with
--enable-feature=promql-experimental-functions
# When did this time series start?
ts_of_first_over_time(metric[24h])
# How long has this metric existed?
time() - ts_of_first_over_time(metric[7d])
Use for: Tracking when metrics first appeared, calculating metric age.
mad_over_time (Experimental)
Calculates the median absolute deviation of all float samples in the specified interval.
Requires Feature Flag: Must enable with
--enable-feature=promql-experimental-functions
# Median absolute deviation of CPU usage over 1 hour
mad_over_time(cpu_usage_percent[1h])
# Detect anomalies: values far from median
metric > avg_over_time(metric[1h]) + 3 * mad_over_time(metric[1h])
Use for: Anomaly detection, measuring variability robustly (less sensitive to outliers than stddev).
sort_by_label (Experimental)
Returns vector elements sorted by the values of the given labels in ascending order.
Requires Feature Flag: Must enable with
--enable-feature=promql-experimental-functions
# Sort by service name
sort_by_label(up, "service")
# Sort by multiple labels
sort_by_label(http_requests_total, "job", "instance")
How it works:
- Sorts by the specified label values alphabetically
- If label values are equal, elements are sorted by their full label sets
- Acts on both float and histogram samples
- Only affects instant queries (range queries have fixed ordering)
Use for: Organizing query results for display, dashboard ordering.
sort_by_label_desc (Experimental)
Same as sort_by_label, but sorts in descending order.
Requires Feature Flag: Must enable with
--enable-feature=promql-experimental-functions
# Sort by service name (descending)
sort_by_label_desc(up, "service")
Use for: Reverse alphabetical ordering of results.
Math Functions
Mathematical operations on metric values.
abs
Returns absolute value.
# Absolute value of temperature difference
abs(current_temp - target_temp)
ceil / floor
Rounds up or down to nearest integer.
# Round up CPU count
ceil(cpu_count_fractional)
# Round down memory in GB
floor(memory_bytes / 1024 / 1024 / 1024)
round
Rounds to nearest integer or specified precision.
# Round to nearest integer
round(cpu_usage_percent)
# Round to nearest 0.1
round(response_time_seconds, 0.1)
# Round to nearest 10
round(request_count, 10)
sqrt
Calculates square root.
# Standard deviation calculation
sqrt(avg(metric^2) - avg(metric)^2)
exp / ln / log2 / log10
Exponential and logarithmic functions.
# Natural exponential
exp(log_scale_metric)
# Natural logarithm
ln(exponential_metric)
# Base-2 logarithm
log2(power_of_two_metric)
# Base-10 logarithm
log10(large_number_metric)
clamp / clamp_max / clamp_min
Limits values to a range.
# Clamp between 0 and 100
clamp(metric, 0, 100)
# Cap at maximum
clamp_max(metric, 100)
# Ensure minimum
clamp_min(metric, 0)
Use for: Normalizing values, preventing display overflow.
sgn
Returns sign of value: 1 for positive, 0 for zero, -1 for negative.
# Get sign of temperature delta
sgn(current_temp - target_temp)
Native Histogram Functions (Prometheus 3.x+)
Native histograms are now stable in Prometheus 3.x. These functions work with native histogram data.
histogram_quantile (Native Histograms)
For native histograms, the syntax is simpler - no _bucket suffix or le label needed:
# Native histogram quantile (simpler syntax)
histogram_quantile(0.95,
sum by (job) (rate(http_request_duration_seconds[5m]))
)
# Compare with classic histogram (requires _bucket and le)
histogram_quantile(0.95,
sum by (job, le) (rate(http_request_duration_seconds_bucket[5m]))
)
histogram_count
Extracts the count of observations from a native histogram.
# Rate of observations per second
histogram_count(rate(http_request_duration_seconds[5m]))
# Total observations in time window
histogram_count(increase(http_request_duration_seconds[1h]))
Use for: Getting request counts from native histogram metrics.
histogram_sum
Extracts the sum of observations from a native histogram.
# Sum of all observation values
histogram_sum(rate(http_request_duration_seconds[5m]))
# Average value from native histogram
histogram_sum(rate(http_request_duration_seconds[5m]))
/
histogram_count(rate(http_request_duration_seconds[5m]))
Use for: Calculating averages, total latency.
histogram_fraction
Calculates the fraction of observations between two values in a native histogram.
# Fraction of requests under 100ms
histogram_fraction(0, 0.1, rate(http_request_duration_seconds[5m]))
# Percentage of requests between 100ms and 500ms
histogram_fraction(0.1, 0.5, rate(http_request_duration_seconds[5m])) * 100
# SLO compliance: percentage under threshold
histogram_fraction(0, 0.2, rate(http_request_duration_seconds[5m])) >= 0.95
Use for: SLO compliance calculations, distribution analysis.
histogram_stddev
Calculates the estimated standard deviation of observations in a native histogram.
# Standard deviation of request durations
histogram_stddev(rate(http_request_duration_seconds[5m]))
How it works:
- Assumes observations within a bucket are at the mean of bucket boundaries
- For zero buckets and custom-boundary buckets: uses arithmetic mean
- For exponential buckets: uses geometric mean
- Float samples are ignored and do not appear in the returned vector
Use for: Understanding variability in metrics, anomaly detection.
histogram_stdvar
Calculates the estimated standard variance of observations in a native histogram.
# Standard variance of request durations
histogram_stdvar(rate(http_request_duration_seconds[5m]))
# Compare variance across services
histogram_stdvar(sum by (service) (rate(http_request_duration_seconds[5m])))
How it works:
- Same estimation method as
histogram_stddev(variance = stddev²) - Assumes observations within a bucket are at the mean of bucket boundaries
- For zero buckets and custom-boundary buckets: uses arithmetic mean
- For expone