Course contentsShow
← Cloud and Infrastructure
Lesson 1975 of 2,98942. Observability - MetricsFree lesson

Subqueries and Complex Expressions

Build nested queries with subqueries to perform advanced calculations on time-windowed data.

Subqueries and Complex Expressions

What you'll learn: How to nest queries inside other queries to perform multi-layered calculations on time-windowed metric data.

What Are Subqueries?

A PromQL subquery lets you execute a query, then treat its result as the input to an outer query. Think of it like a "query within a query"—the inner query runs first over a specific time range, then the outer query processes those results.

Why use subqueries? Sometimes you need to calculate a metric over a sliding window, then perform another aggregation or function on that result. For example, finding the maximum of a 5-minute rate over the past hour, or detecting when a derived metric crosses a threshold multiple times.

Subquery Syntax

The basic pattern is:

<query>[<range>:<resolution>]
  • <query>: Any valid PromQL expression
  • <range>: Time window to evaluate (e.g., 5m, 1h)
  • <resolution>: Optional sampling step (defaults to global interval)

Example:

max_over_time(rate(http_requests_total[5m])[1h:])

This calculates the rate() over 5-minute windows, then finds the max_over_time() of those rates across the last hour.

Building Complex Expressions

Combine subqueries with:

  • Aggregation operators (sum, avg, max)
  • Binary operators for arithmetic
  • Label matching to correlate metrics
avg_over_time(
  sum by (job) (rate(cpu_usage[2m]))[10m:]
) > 0.8

This averages the per-job CPU rate over a 10-minute subquery window and filters results exceeding 80%.

When to Use Subqueries

Use them when you need to "double-aggregate" or analyze trends of already-computed metrics—like detecting spikes in error rates or smoothing volatile gauge changes.

Key Takeaway: Subqueries enable multi-layer analysis by treating query results as time-series inputs for outer functions, unlocking advanced metric calculations over flexible time windows.