Sub topic 3
How iterators work: table, expression, aggregation
This chapter assumes you know the basics of a Power BI or Analysis Services tabular model (tables, columns, relationships). It also assumes you can write simple measures with SUM, COUNT, and CALCULATE, and that you are comfortable with fact and dimension tables in a star schema. Here we build the working model that SUMX, AVERAGEX, and RANKX share. Later chapters cover each function in detail.
Two contexts, two jobs
DAX evaluates every expression inside two kinds of context. Iterators are the place where both are active at once.
- Filter context is the set of filters that decides which rows of each table a calculation can see. Slicers, report filters, rows and columns of a visual, and CALCULATE filters all create it. A measure such as
SUM ( Sales[Quantity] )reads whatever rows survive the filter context. - Row context points at one row of one table. It lets an expression refer to the columns of that row directly, as in
Sales[Quantity]. Calculated columns get a row context automatically. Measures do not.
Row context does not filter anything. It marks a current row. Filter context filters tables. Keeping these two ideas separate explains most iterator behavior.
The three parts of an iterator
Most iterators are functions whose names end in X, such as SUMX, AVERAGEX, COUNTX, MINX, and MAXX. They all follow the same pattern:
<Aggregation>X ( <table>, <expression> )- Table. The function evaluates this argument first, in the current filter context. The result is the list of rows to visit.
- Expression. For each row of that table, DAX creates a row context and evaluates the expression once.
- Aggregation. The function combines the per-row results. SUMX adds them, AVERAGEX averages them, MINX takes the smallest, and so on.
The standard first example is a sales amount that needs quantity times price on each row:
Sales Amount =
SUMX (
Sales,
Sales[Quantity] * Sales[Net Price]
)SUM cannot do this. SUM accepts one column, so it cannot multiply two columns row by row before adding. SUMX can, because the expression runs inside a row context where both Sales[Quantity] and Sales[Net Price] refer to the same row.
A worked example
Suppose a report cell has a filter context that leaves three rows of Sales:
| Row | Quantity | Net Price | Expression result |
|---|---|---|---|
| 1 | 2 | 10 | 20 |
| 2 | 1 | 50 | 50 |
| 3 | 3 | 20 | 60 |
The table argument Sales returns those three rows because the filter context removed all others. The expression runs three times and produces 20, 50, and 60. SUMX adds them and returns 130.
Change the slicer so only rows 1 and 3 remain visible, and the same measure returns 80. The measure never changed. Only the table it iterated changed.
SUM is a shortcut for an iterator
SUM ( Sales[Quantity] ) behaves as if you had written SUMX ( Sales, Sales[Quantity] ). The engine treats the single-column form as a shorthand. The same holds for AVERAGE and AVERAGEX, MIN and MINX, and MAX and MAXX. The X version accepts a table and any scalar expression instead of one column. Use the plain aggregator when you only need one column. It states the intent and is usually at least as fast.
Order of evaluation matters
The table argument is evaluated once, outside the loop, in the filter context of the caller. The expression is evaluated inside the loop, in that same filter context plus one row context per visited row. Two consequences follow.
- Filters you want to apply to the rows go in the table argument, not inside the expression. For example,
SUMX ( FILTER ( Sales, Sales[Quantity] > 1 ), ... )limits the rows visited. - A row context does not narrow the filter context. If the expression calls a measure, that measure still sees the outer filter context unless something converts the row into a filter. That conversion is called context transition, and a later chapter covers it.
What happens with the results
The aggregation step has rules about blanks and empty input. These matter when you compare iterators.
| Function | Aggregation | Blank per-row results |
|---|---|---|
| SUMX | Sum | Treated as nothing added |
| AVERAGEX | Mean | Skipped, not counted in the divisor |
| MINX, MAXX | Smallest, largest | Skipped |
| COUNTX | Count of non-blank results | Not counted |
If the table argument returns no rows, SUMX returns BLANK, not 0. If every per-row result is blank, the result is also BLANK. A visual usually hides rows whose measure is BLANK, which is one reason a product with no sales can disappear from a table. If you want zeros, add + 0 or wrap the result with COALESCE, and be aware that doing so makes every product appear.
Common errors
Using a column outside any row context
A measure has no row context of its own. This measure fails:
Bad Amount =
Sales[Quantity] * Sales[Net Price]DAX reports that a single value for the column cannot be determined, because the filter context may contain many rows. Wrap the expression in an iterator that supplies the row context:
Good Amount =
SUMX (
Sales,
Sales[Quantity] * Sales[Net Price]
)The same expression works without an iterator inside a calculated column, because the engine creates a row context for each row of the table when it computes the column:
Line Amount = Sales[Quantity] * Sales[Net Price]Iterating a table you do not need
SUMX ( Sales, ... ) visits every row of Sales that is visible in the filter context. If the model has 100 million visible rows, the expression is evaluated 100 million times. Iterate over a smaller table when the result allows it. For example, iterating over VALUES ( Product[Category] ) visits one row per category. The right table also determines the meaning of the answer, which the chapter on choosing the table argument discusses.
Mixing up the table and the expression
The table argument must return a table. The expression must return a single value for the current row. SUMX ( Sales[Quantity], ... ) is invalid because a column is not a table. A column reference by itself is a scalar in a row context, not a table.
Nested iterators
An iterator can appear inside another iterator's expression. Each level adds its own row context, and the inner expression can read columns from every enclosing row. The outer row context stays active until the outer expression finishes.
Sales Amount Nested =
SUMX (
VALUES ( 'Date'[Date] ),
SUMX (
RELATEDTABLE ( Sales ),
Sales[Quantity] * Sales[Net Price]
)
)Here the outer loop visits each visible date. For each date, RELATEDTABLE returns the Sales rows linked to that date, and the inner loop sums them. The total equals the plain Sales Amount, but the nesting does more work than needed. Nested iterators multiply their cost: the inner expression runs once per inner row for every outer row. Use nesting only when the outer level is needed to produce a different result, such as aggregating per day before summing.
Choosing between an iterator and an aggregator
Pick the aggregator, such as SUM or AVERAGE, when one column holds the value you need. Pick the iterator when the value requires a calculation on each row before combining, such as quantity times price. Also pick an iterator when you need to average, rank, or compare values that are themselves measures over a set of members. Those cases appear in the AVERAGEX and RANKX chapters.
Exercise
A report cell's filter context leaves these Sales rows: (Quantity 4, Net Price 5), (Quantity 2, Net Price 15), (Quantity 1, Net Price blank). What does SUMX ( Sales, Sales[Quantity] * Sales[Net Price] ) return, and in what order does DAX perform the three parts?
Show answer
It returns 50. The table argument Sales is evaluated first in the filter context and gives three rows. The expression then runs once per row: 20, 30, and a blank multiplication that DAX treats as 0 for the product of a number and a blank. Finally SUMX adds the results: 20 + 30 + 0 = 50.
Exercise
You write the measure Margin = Sales[Net Price] - Sales[Unit Cost] and get an error about a single value that cannot be determined. Why does it fail, and how do you fix it?
Show answer
A measure has no row context, so the column references have no current row to refer to, and the filter context may contain many rows. Put the calculation in an iterator that supplies a row context, for example SUMX ( Sales, Sales[Net Price] - Sales[Unit Cost] ) when both columns exist in Sales. If Unit Cost is in a related table, use RELATED, which a later chapter covers.