Sub topic 2
Row context and iterators in brief
This chapter assumes you can write basic measures with SUM and COUNTROWS. It also assumes you know how relationships link tables in a model, and that you have seen slicers and visuals filter a report. The previous chapter covered filter context. This chapter covers the second kind of context in DAX, row context. The FILTER function is built on it.
Two contexts, two jobs
DAX evaluates every expression inside a context. There are two kinds, and they do different jobs.
- Filter context is a set of filters on columns. It decides which rows of the model an aggregation can see. Slicers, visual rows and columns, and
CALCULATEfilter arguments all create it. - Row context is a pointer to one row of one table. It lets an expression read that row's column values. It does not filter anything.
The second point trips up many learners. A row context on Sales lets you write Sales[Quantity] and get one number, the quantity of the current row. It does not restrict what SUM ( Sales[Amount] ) sees. Aggregations respond only to filter context.
| Property | Filter context | Row context |
|---|---|---|
| What it holds | Filters on columns | A current row of one table |
| Who creates it | Slicers, visuals, `CALCULATE` | Calculated columns, iterator functions |
| What it affects | Aggregations such as `SUM` | Direct column references such as `Sales[Quantity]` |
| Follows relationships | Yes, along filter direction | No, only with `RELATED` or `RELATEDTABLE` |
Where row context comes from
Row context appears in two places.
Calculated columns
A calculated column is evaluated once for every row of its table when the model refreshes. DAX opens a row context on that table and runs the expression once per row.
Line Amount = Sales[Quantity] * Sales[Net Price]For each row of Sales, the expression reads that row's Quantity and Net Price and multiplies them. The result is stored in the model, so it uses memory and is not affected by slicers.
Iterator functions
An iterator is a function that walks through a table one row at a time. For each row it creates a row context and evaluates an expression. It then combines the per-row results. Iterators in DAX have names ending in X.
| Iterator | Per-row result is combined by |
|---|---|
| `SUMX` | Adding |
| `AVERAGEX` | Averaging |
| `MINX`, `MAXX` | Taking the smallest or largest |
| `COUNTX` | Counting non-blank values |
| `FILTER` | Keeping the rows where the expression is true |
Every iterator has the same shape: a table, then an expression to evaluate for each row.
Total Line Amount =
SUMX ( Sales, Sales[Quantity] * Sales[Net Price] )The first argument is the table to walk through. The second is evaluated once per row, inside a row context on Sales. SUMX then adds up the results.
Why SUM cannot do this
A common first attempt is to put an expression inside SUM.
-- This does not work
Broken Total = SUM ( Sales[Quantity] * Sales[Net Price] )SUM accepts only a single column reference. It is a shortcut that wraps SUMX around one column. There is no row context in a plain measure, so Sales[Quantity] on its own has no current row to read. The fix is to use an iterator, as in Total Line Amount above. Alternatively, store the product in the calculated column Line Amount and sum that.
The two options trade off as follows.
| Approach | Strength | Cost |
|---|---|---|
| `SUMX` over a table | No extra storage, responds to filter context | Computed at query time |
| Calculated column plus `SUM` | Simple measure, value precomputed | Uses memory, increases refresh time |
For simple arithmetic across columns of one table, SUMX is usually the better choice.
Seeing the iteration
The diagram shows what SUMX does with a three-row filtered table.
The order matters. Filter context runs first and decides which rows exist. The iterator then adds row context on top of those rows. This is why a SUMX measure still responds to slicers, even though it walks row by row.
FILTER is an iterator that returns a table
Most iterators return one value. FILTER returns a table. It walks through the table you give it, evaluates a true or false condition for each row, and keeps the rows where the condition is true.
Large Line Sales =
CALCULATE (
[Total Sales],
FILTER ( Sales, Sales[Quantity] * Sales[Net Price] > 1000 )
)The condition multiplies two columns of the same row. That is only possible because FILTER opens a row context on Sales for each row. A boolean filter argument such as Sales[Amount] > 1000 cannot express a condition that combines columns this way, which is the reason to reach for FILTER. The later chapter on FILTER covers when to use each form.
The signature is FILTER ( <table>, <condition> ). Two details are worth fixing in your head now.
- The first argument is evaluated in the current filter context. If a slicer already limits
Salesto 2025,FILTER ( Sales, ... )only walks through 2025 rows. Wrapping it inCALCULATEcan then add or replace filters, depending on what you pass. - The output has the same columns as the input table, with fewer rows.
CALCULATEuses those rows as a filter.
Row context does not cross relationships
Row context sees only the table it was opened on. If a Sales row has a ProductKey, the row context does not automatically give you the product's cost. Filter context flows from the one side of a relationship to the many side. Row context does not flow at all.
To reach a column on the one side from a row context on the many side, use RELATED. This example assumes 'Product' has a Unit Cost column.
Line Margin =
Sales[Quantity] * ( Sales[Net Price] - RELATED ( 'Product'[Unit Cost] ) )This is a calculated column on Sales. RELATED follows the relationship from the current Sales row to its single matching Product row.
The reverse direction needs RELATEDTABLE. A row context on Product can call RELATEDTABLE ( Sales ) to get the Sales rows that belong to that product. That returns a table, so you wrap it in an aggregator such as COUNTROWS.
Sales Row Count = COUNTROWS ( RELATEDTABLE ( Sales ) )Used as a calculated column on Product, this counts the sales rows of each product.
Context transition: when a row becomes a filter
Row context and filter context stay separate until CALCULATE joins them. When CALCULATE is evaluated inside a row context, DAX converts the current row into an equivalent set of filters on every column of that row's table. This is called context transition.
You rarely see CALCULATE written to trigger it, because referencing a measure always wraps the measure in an implicit CALCULATE. That gives a useful and surprising result.
Average Sales per Category =
AVERAGEX (
VALUES ( 'Product'[Category] ),
[Total Sales]
)VALUES ( 'Product'[Category] ) returns the categories visible in the current filter context. AVERAGEX walks through them, one row context per category. For each category, [Total Sales] is evaluated. Because a measure reference carries an implicit CALCULATE, the current category becomes a filter, and [Total Sales] returns that category's sales. AVERAGEX then averages those values.
If you replace [Total Sales] with SUM ( Sales[Amount] ), you get a different result. A bare SUM has no implicit CALCULATE, so no transition occurs. Every iteration sees the same total, and the average is just the overall total. This is one of the most common reasons an iterator "ignores" its row.
-- Same total on every row: no context transition
Wrong Average per Category =
AVERAGEX (
VALUES ( 'Product'[Category] ),
SUM ( Sales[Amount] )
)Edge cases and gotchas
Iterating a large table is more expensive than iterating a small one
SUMX ( Sales, ... ) visits every visible row of Sales. On a fact table with hundreds of millions of rows, a complex expression can be slow. Simple arithmetic over one table is usually fine, because the engine can often compute it in one pass. The risk grows with a measure reference inside the iterator, because each row triggers context transition and a separate evaluation. Iterate over the smallest table that gives the grain you need. VALUES ( 'Product'[Category] ) has a handful of rows. Sales may have millions.
A row context can nest
An iterator inside an iterator creates nested row contexts. The inner expression can read columns from both tables. When both loops run over the same table, the inner row context hides the outer one, and the outer row can no longer be read directly. Avoid this by iterating over different tables, or by storing the outer value in a variable first.
Sales Above Category Average =
VAR CategoryAverage =
AVERAGEX ( ALLSELECTED ( Sales ), Sales[Quantity] * Sales[Net Price] )
RETURN
SUMX (
FILTER ( Sales, Sales[Quantity] * Sales[Net Price] > CategoryAverage ),
Sales[Quantity] * Sales[Net Price]
)The variable CategoryAverage is computed once, before the loop starts. The FILTER condition then compares each row to a fixed number. Despite its name, the variable holds the average of all selected sales lines. It is not grouped by category. Rename it in your own model if that matches your intent better. ALLSELECTED is covered in a later chapter. Here it only supplies a table to average over.
Blank and error rows
An iterator treats a blank per-row result differently from a zero in some functions. SUMX ignores blanks. COUNTX counts only non-blank results. AVERAGEX leaves blanks out of both the sum and the count. An error in any row, such as a division by zero, makes the whole iterator return an error unless you guard the expression with DIVIDE or IFERROR.
Row context in measures versus calculated columns
A calculated column has a row context automatically, so Sales[Quantity] works there. A measure has none. If you copy the body of a calculated column into a measure, it fails with an error saying a single value cannot be determined. Wrap the expression in an iterator to restore the row context.
Summary of rules
- Filter context decides which rows are visible. Row context points to one row. Only filter context restricts aggregations.
- Calculated columns and iterators (
SUMX,AVERAGEX,FILTER, and others) create row context. - A measure on its own has no row context. Use an iterator when you need to evaluate an expression per row.
- Row context does not follow relationships. Use
RELATEDorRELATEDTABLE. - Referencing a measure inside a row context triggers context transition, and the row becomes a filter.
FILTERis an iterator that returns the rows for which its condition is true.
Exercise
A colleague writes the measure Revenue = SUM ( Sales[Quantity] * Sales[Net Price] ) and gets an error. Explain why it fails and write two working alternatives.
Show answer
SUM accepts only a single column reference, and a measure has no row context in which Sales[Quantity] * Sales[Net Price] could be evaluated for a current row. One fix is an iterator: Revenue = SUMX ( Sales, Sales[Quantity] * Sales[Net Price] ). The other is to add a calculated column Line Amount = Sales[Quantity] * Sales[Net Price] and then write Revenue = SUM ( Sales[Line Amount] ).
Exercise
Two measures iterate over the visible categories. Measure A is AVERAGEX ( VALUES ( 'Product'[Category] ), [Total Sales] ). Measure B is AVERAGEX ( VALUES ( 'Product'[Category] ), SUM ( Sales[Amount] ) ). Which one returns the average of per-category sales, and why does the other not?
Show answer
Measure A does. Referencing the measure [Total Sales] inside the iterator adds an implicit CALCULATE, so context transition turns each category row into a filter and the sum is computed per category. In measure B the bare SUM triggers no context transition, so each iteration sees the same filter context and returns the same overall total. The average is then just that total.
Exercise
Why can FILTER ( Sales, Sales[Quantity] * Sales[Net Price] > 1000 ) express a condition that a simple boolean filter argument inside CALCULATE cannot?
Show answer
FILTER is an iterator. It opens a row context on Sales for each row, so the condition can read and combine several columns of the same row. A boolean filter argument in CALCULATE is limited to conditions on a single column, so it cannot multiply two columns of one row.