Grafana: Transformations and Expressions
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Checked on 2026-11-09 against Grafana 13.3.x.
To do this by hand, follow Transformations and Expressions.
A query returns what the data source knows; a panel needs what the reader wants to see. The gap is bridged in two places. Transformations reshape the data frames in the panel, after the query and before the visualization: rename columns, join two queries into one table, keep only the rows above a threshold. Expressions compute new data on the Grafana server from the results of queries: the mechanism alert rules use, because an alert rule has no panel and no browser. SQL expressions are the third option, a SQL query over the results of other queries. This page explains how each works, which tool to reach for, and what goes wrong.
The query side is in Queries, Explore and Drilldown; the visualizations that consume the result are in Choosing a Visualization; the alert rules that use expressions are in Alerting Fundamentals.
Data frames in one paragraph
Every query result reaches Grafana as one or more data frames: a table with typed fields (time, number, string) in which a field can carry labels. A Prometheus range query returns one frame per series, each with a time field and a value field whose labels are the series labels; a SQL query returns one frame with a column per field. Transformations operate on frames, and the Table view toggle above a visualization (and the Data tab of the query inspector) shows what the frames look like at that point. Some transformed data cannot be graphed, so when a panel goes blank after a transformation, switch to the table view first.
Source: Grafana: Transform data.
The transformation pipeline
Order, debug, disable and apply to
Transformations run in the order of the cards in the panel editor, and each takes the output of the previous one. Order therefore changes results: a Reduce that collapses a column to one value leaves only that value to the steps after it, and a Filter data by values placed before a Group by filters rows while one placed after it filters groups. Chaining small transformations is also cheaper than one clumsy one. Salituro (see below) adds the point that the pipeline is one-way: the transformed data cannot be queried again as if it were a data source.
The editor gives four controls, which are the way to debug a pipeline:
-
Add: the plus icon next to Transformations in the editor sidebar, or the plus beside a card to insert after it; drag cards to reorder.
-
Debug (bug icon): shows the input and the output result of the selected transformation. Use it on the first card whose output is not what you expect.
-
Disable (eye icon): turns a card off without deleting it; bisect a broken pipeline by disabling from the bottom up.
-
Apply transformation to (filter icon): when a panel has several queries (or annotation and exemplar data), limit a card to one of them. It may not work after an earlier merge, which combines the outputs. A separate transformation, Filter data by query refId, shows or hides whole queries by letter.
Text inputs accept dashboard variable syntax, interpolated before the transformation runs. Some transformations build output refIds from their inputs
(merge-A-B); a static refId gives such a transformation a fixed name so later filters survive when the queries change (it
cannot contain variables, duplicate another transformation’s name or match a query refId).
Source: Grafana: Transform data, sections order of transformations, debug, disable, filter and static refId.
The transformations worth knowing
The reference lists a long catalogue of transformations; these are the ones that earn their place in operational dashboards.
| Transformation | What it does | Bookshelf use |
|---|---|---|
Reduce |
Collapses each field to a single calculated value. Series to rows gives one row per series with a column per calculation; Reduce fields keeps the structure and adds a row per calculation. It removes the time field. |
"Last, max and mean p95 per route" as a table from a time series query. |
Merge series/tables |
Combines several query results into one table, merging rows that share the same field values. |
Several instant queries (one per metric) into a single table of routes. |
Join by field |
Joins results on a shared field, usually time, into one wide table. Inner join and outer join (time series or SQL-like) exist; Keep unjoined keeps rows without a match on earlier joins. |
Requests and errors from two queries in one table by route. |
Organize fields by name |
Renames, reorders or hides fields of a single query. |
Turning |
Filter data by values |
Includes or excludes rows by conditions on a field (greater, regex, in between …), matching all or any condition. |
Only routes whose error ratio is above 1 percent. |
Group by |
Groups rows by a field and calculates per group. |
Errors by |
Partition by values |
Splits one result into separate series by the unique values of chosen fields. |
One line per instance from a SQL query returning (time, instance, value). |
Add field from calculation |
Adds a field computed from others: row-wise reduce, binary operation, unary, cumulative, window, row index. |
Error ratio as errors divided by requests, when both are separate fields. |
Config from query results |
Takes thresholds, min, max, unit or value mappings from one query and applies them to another. |
Colour a Stat with the SLO threshold stored in PostgreSQL. |
Sort by |
Sorts each frame by a field, optionally reversed. |
A top-N table of the slowest routes. |
Trendline |
Adds a frame with the values of a fitted linear or polynomial regression model. |
A quick trend over the memory series. |
Labels to fields |
Turns series labels into columns or rows. |
Making the |
Rename by regex, Convert field type, Prepare time series |
Rename fields with back references, change a field’s type (numeric, string, time, boolean …), and convert between wide, multi-frame and long time series. |
Fixing a numeric column that arrived as text; adapting a SQL result to a time series panel. |
Caveats the documentation lists, each of which has cost someone an afternoon:
-
Joins drop rows or queries that lack the join field unless Keep unjoined is enabled; inner joins are not optimised for large time series data sets.
-
Organize fields by name works only on single-query panels; Labels to fields always runs an internal merge that cannot be turned off.
-
Reduce removes time fields; Filter data by values ignores invalid or incomplete conditions (a typo gives all rows rather than an error).
-
Since 9.0, Rename by regex accepts global patterns, which can change the behaviour of old patterns; wrapping them in slashes restores the old behaviour.
Source: Grafana: Transform data, reference and the subsections Join by field, Filter data by values, Config from query results.
A pipeline in the UI and as code
A "slowest routes" table for Bookshelf: one instant Prometheus query (format Table or time series) with the p95 per route, then
three transformations. In the dashboard JSON the pipeline is the transformations array of the panel, in the same order as the
cards:
{
"type": "table",
"title": "Slowest routes (p95)",
"datasource": { "type": "prometheus", "uid": "prometheus" },
"targets": [
{
"refId": "A",
"expr": "histogram_quantile(0.95, sum by (le, uri) (rate(http_server_requests_seconds_bucket{application=\"bookshelf\"}[$__rate_interval])))"
}
],
"transformations": [
{
"id": "reduce",
"options": { "mode": "seriesToRows", "reducers": ["lastNotNull", "max"] }
},
{
"id": "filterByValue",
"options": {
"type": "include",
"match": "any",
"filters": [
{ "fieldName": "Max", "config": { "id": "greater", "options": { "value": 0.5 } } }
]
}
},
{
"id": "sortBy",
"options": { "sort": [{ "field": "Max", "desc": true }] }
}
]
}
The id values are the transformer identifiers of Grafana’s source (reduce, filterByValue, sortBy, organize,
joinByField, merge, groupBy, partitionByValues, calculateField, configFromData, labelsToFields, regression
for Trendline); the quickest way to get the options of any other transformation is to build it in the UI and read the panel in
the dashboard’s JSON model (see Library Panels, JSON Model and Versions).
The exact field names in fieldName are the display names after the previous steps (here the Reduce output column "Max"),
which is why Debug is the tool to check them.
Reference: Grafana source: transformer IDs and Grafana: Transform data.
Verify in the lab: build the panel, then open Inspect > Data and the Debug view of each card to see how the rows change; disable the Filter card and check that the table grows; reorder Sort before Reduce and see that the order is lost.
Calculation types
Reduce, Add field from calculation, the legend of a time series, the value of a Stat and the table footer all use the same list of calculation types. The ones that matter in monitoring:
-
Last and its not-null variant, listed as
Last *: the last value, and the last value that is neither null nor NaN. A Stat that shows "N/A" or zero during a scrape gap usually wants the not-null variant. -
Mean, Min, Max, Total, Median, Count, Range (max minus min) and the percentile entries 1st % to 99th % of the values in the series (these are percentiles of the displayed samples, not of the underlying request population; see Metric Types and Aggregation for why averaging or reducing already aggregated percentiles misleads).
-
Delta (cumulative change counting only increases), Difference (last minus first), Difference percent, Step (smallest interval between values) and Change count.
-
Distinct count, All unique values, First, Min (above zero), StdDev, Variance, All nulls and All zeros.
Source: Grafana: Calculation types.
Server-side expressions
Expressions create new data from the results of queries; they do not change what the data source returned. They are mostly used by Grafana Alerting, because the evaluation runs on the server without a browser, and they can also be used in panels. The rules that matter:
-
They work with backend data sources (Prometheus, Loki, SQL and most others) and not with the Dashboard data source.
-
They handle two kinds of collections, time series and numbers, each item identified by its labels (dimensions), so multi-dimensional data is supported and an alert rule can evaluate one instance per label set.
-
A query or expression is referred to by its RefID with a dollar sign:
$A; a name with spaces uses braces. -
If any queried data source returns no series or numbers, the whole result is
NoData, which alerting then handles with its no-data settings (see Designing Actionable Alerts). -
They are meant for lightweight processing: compute inside the data source when possible, since copying data to the Grafana server is inefficient.
Math
Free-form formulas over numbers and series: arithmetic operators (addition, subtraction, multiplication, division /, modulo, exponent), relational and logical operators
(returning 1 for true and 0 for false) and functions (abs, round, ceil, floor, log, is_nan, is_null, is_inf …). Number with series gives a series;
series with series is applied at the timestamps they share (so resample first); binary operations join items by labels, where an
unlabelled item joins with anything and a subset of labels also matches. Inconsistent label keys in one variable give undefined joins.
Example, the Bookshelf error ratio from two queries when you cannot do the division in one PromQL expression: query A returns the 5xx rate, query B the total rate, and the Math expression is
$A / $B
and it then feeds a Reduce and a threshold. When both parts come from the same Prometheus, divide in PromQL instead: the data source does the work and there is no label-join surprise.
Reduce
Turns each time series into one number while keeping its labels. Choose the function (Count, Mean, Min, Max, Sum, Last), the input and the mode: Strict returns NaN if any value is non-numeric, Drop Non-Numeric filters those values out first, Replace Non-Numeric substitutes a value. A rule that evaluates "the last value" with Strict mode turns a single null into NaN, and what that means for the alert is decided by the no-data and error handling of the rule; Drop Non-Numeric is usually the safer choice for gappy series.
Resample
Aligns series to a common interval so Math between series with different timestamps works. Set the input, Resample to (for
example 10s; units s, m, h, d, w, y), Downsample (how to reduce several points in a window) and Upsample (fill empty
windows with pad the last value, backfill the next value or fillna NaN).
Source: Grafana: Use expressions to manipulate data. The alert condition that finishes a rule is described with the rule in Alerting Fundamentals.
SQL expressions
A SQL expression runs a SQL query over the results of other queries, treating each query’s RefID as a table. It is enabled by default in Grafana 13.3 (no feature toggle), uses a MySQL-like syntax with an allowlist of supported keywords and functions, and has a few firm requirements:
-
The panel or rule must use a backend data source (not the Dashboard data source), and the query needs a time range.
-
A SQL expression can reference only data source queries, not other expressions, and only one SQL expression is allowed per panel or alert.
-
Regular expressions use Go’s RE2 syntax, with no back references or lookaround.
-
Limits in the
[expressions]section of the configuration: input cells 100000 (the query fails above), output cells 100000 (the result is truncated with a warning), query length 10000 characters, and timeout 10 seconds (the query is cancelled);0disables a limit. -
Results of Prometheus-style (non-tabular) queries are converted to a long table: label keys become columns and the value goes to a value column. Check the real column names in the Schema inspector of the editor, because they depend on the format of the query.
For alerting and recording rules the result must have exactly one numeric column and a unique combination of string column values on each
row; the other string columns become labels (one alert instance per row). Use GROUP BY to avoid duplicate-label errors and keep label cardinality low. A
SQL expression also protects against the classic Prometheus no-data problem: a FULL OUTER JOIN with COALESCE guarantees
a row when one of the two queries returns nothing, whereas errors, empty results and changing label sets can break the static
schema SQL expects, so avoid SELECT * and select explicit columns.
Example in the shape the documentation gives: queries A (5xx rate per route) and B (total rate per route) joined into an error
ratio per route, one alert instance per route. The value column name is whatever the Schema inspector shows for your queries;
replace value accordingly.
SELECT
B.uri,
COALESCE(A.value, 0) / B.value AS error_ratio
FROM B
FULL OUTER JOIN A ON A.uri = B.uri
Reference: Grafana: SQL expressions (limits, alerting requirements and known limitations).
Choosing between the three
| Need | Use | Why |
|---|---|---|
Rename, hide or order columns; join two queries into a table; threshold colours from another query |
Transformations |
Presentation only, applied in the panel after the data arrives |
Compute a value an alert rule evaluates, from one or several queries |
Server-side expressions (Math, Reduce, Resample) or a SQL expression |
Runs on the server without a browser; handles NoData through the rule’s settings |
Join, filter and aggregate several queries relationally for a rule or a table |
SQL expression |
One declarative statement instead of a chain of cards; mind the cell limits |
Anything the data source can compute itself (rates, quantiles, ratios, group by) |
The query |
Cheapest: less data crosses the network and the result is the same in every panel and alert |
In the books
Salituro (Learn Grafana 10.x) devotes a chapter to data frames and the transformation functions (adding, modifying, filtering, reducing and combining fields, chaining them into a pipeline) with TestData as the practice source; the concepts, including the one-way pipeline and the fact that a visualization sees the result of the last enabled transformation, are unchanged. What the book cannot show: the Grafana 13 editor (sidebar with queries, expressions and transformations as cards, debug and apply-to controls), the Trendline transformation, server-side expressions as a first-class part of alert rules, and SQL expressions, which are new. Check the transformation names against the reference above before following a recipe.