Sub topic 12
Nested Row Contexts, EARLIER, and Variables
This chapter assumes you know the following:
- How a row context works inside a calculated column or an iterator.
- That CALCULATE and measure references trigger context transition.
- The difference between a measure and a calculated column.
Here you will see what happens when one row context is opened inside another, why that can silently break a formula, and how variables fix it.
What a nested row context is
A row context is nested when an iterator or a calculated column opens a second row context while the first is still active. Common ways to get one:
- A calculated column that calls an iterator such as
FILTERorSUMXover any table. - An iterator inside another iterator.
- An iterator that evaluates a measure, because the implicit CALCULATE can add a filter context on top of the existing row context.
DAX keeps every active row context. Each one is tied to a table, and a column reference such as Product[Unit Price] is resolved against the row context of that table.
Nesting over different tables
When the two row contexts belong to different tables, nothing is ambiguous. Each column name points to exactly one current row.
Line Amount Total =
SUMX (
Customer,
SUMX (
RELATEDTABLE ( Sales ),
Sales[Quantity] * Sales[Unit Price]
)
)This measure assumes Customer is on the one side of a relationship to Sales. The outer SUMX puts one Customer row in context. RELATEDTABLE returns the Sales rows for that customer. The inner SUMX then walks those rows. Inside the inner expression you can read Sales[Quantity] from the Sales row and, if you wanted to, Customer[Name] from the outer row. Both row contexts are active, and they do not clash.
Nesting over the same table
The problem starts when both row contexts belong to the same table. The inner row context hides the outer one for that table's columns. A plain column reference always means "the innermost row of this table."
Suppose you want to rank each product by price, where 1 is the most expensive. A first attempt in a calculated column on Product looks reasonable:
-- Calculated column in the Product table (wrong)
Price Rank Wrong =
COUNTROWS (
FILTER ( Product, Product[Unit Price] > Product[Unit Price] )
) + 1The calculated column provides the outer row context, which is the product being ranked. FILTER opens the inner row context, which scans every product. In the filter condition, both Product[Unit Price] references resolve to the inner row. The test compares each product with itself, is never true, and COUNTROWS returns 0. Every product gets rank 1, and no error is raised.
Reaching the outer row with EARLIER
EARLIER takes a column and returns its value from the previous (outer) row context. The classic fix for the ranking column is:
-- Calculated column in the Product table
Price Rank Earlier =
COUNTROWS (
FILTER ( Product, Product[Unit Price] > EARLIER ( Product[Unit Price] ) )
) + 1For the product being ranked, the formula counts how many products have a higher price, then adds 1. The most expensive product gets rank 1.
EARLIER has two limitations.
- It accepts an optional second argument, the number of row-context levels to step out.
EARLIER ( Product[Unit Price], 2 )skips one level. This quickly becomes hard to read and is easy to get wrong. - It only works where a previous row context exists. If it is used with no outer row context, DAX reports an error saying that
EARLIER/EARLIESTrefers to an earlier row context that doesn't exist.
EARLIEST returns the value from the outermost row context. It is rarely needed.
Capturing the outer row with a variable
A variable (VAR) stores a value under a name. The value is computed once, in the evaluation context where the VAR line appears, and later contexts cannot change it. This makes variables a clean replacement for EARLIER:
-- Calculated column in the Product table
Price Rank =
VAR CurrentPrice = Product[Unit Price]
RETURN
COUNTROWS ( FILTER ( Product, Product[Unit Price] > CurrentPrice ) ) + 1CurrentPrice is evaluated while only the outer row context exists, so it holds the price of the product being ranked. Inside FILTER, Product[Unit Price] is the inner row and CurrentPrice is the fixed outer value. The two never compete.
Variables have these advantages over EARLIER:
- The name says what the value is. You do not need to count context levels.
- The expression is computed once, even if you use the variable several times.
- It works in measures too, where
EARLIERhas no outer row context to refer to. - You can step through the formula one
VARat a time when debugging.
Variables are constants, not live references
A variable is evaluated at the point it is defined. It does not re-evaluate when it is used inside a different filter context. This is the same rule that makes it useful for the rank example, and it also causes a common mistake.
Red Sales Wrong =
VAR s = [Sales Amount]
RETURN
CALCULATE ( s, Product[Color] = "Red" )s is calculated first, in the current filter context. CALCULATE then adds the color filter, but s is already a number, so the filter changes nothing. The measure returns the same value as [Sales Amount]. The fix is to put the measure inside CALCULATE, as in the Red Sales measure from the CALCULATE chapter:
Red Sales =
CALCULATE ( [Sales Amount], Product[Color] = "Red" )A variable is the right tool when you want the value from the current context, either the outer row or the original filter selection. A measure reference is the right tool when you want a calculation that responds to filters applied later.
Variables in measures: capturing the filter selection
Variables also help in measures, where the "outer" context is a filter context. Here is a measure that shows what share of the all-products total the current selection represents:
Share of All Products =
VAR CurrentSales = [Sales Amount]
VAR AllSales =
CALCULATE ( [Sales Amount], REMOVEFILTERS ( Product ) )
RETURN
DIVIDE ( CurrentSales, AllSales )CurrentSales keeps the value for the current selection. AllSales is computed with the Product filters removed. Naming both values makes the final line easy to read and keeps the two evaluations apart.
Nested contexts and context transition
Context transition interacts with nesting in two ways.
- Transition inside an iterator. When an iterator evaluates a measure, as in
AVERAGEX ( Customer, [Sales Amount] ), the current row becomes a filter on the table it came from. If you also nest a second iterator, the measure reference turns every active row context into filters, not only the innermost one. You get the filter for each row context, and they combine by intersection. - Variables defined before a transition. A variable captured before
CALCULATEis not affected by the transition. This is useful when you need an outer row value to survive into an expression that also performs context transition.
-- Calculated column in the Product table
Sales of Products at Same Price =
VAR CurrentPrice = Product[Unit Price]
RETURN
SUMX (
FILTER ( Product, Product[Unit Price] = CurrentPrice ),
[Sales Amount]
)The variable holds the outer product's price. FILTER keeps the products with that price. SUMX iterates those products and evaluates [Sales Amount] for each one through context transition. The result is the total sales of all products that share this product's price, including the product itself.
Choosing between EARLIER, variables, and other tools
| Situation | Preferred approach |
|---|---|
| Need the outer row value inside an inner iterator | A `VAR` defined before the inner iterator |
| Reading a column from the outer row, two or more levels up | Several variables, one per level, named for what they hold |
| Ranking rows | `RANKX`, or the `VAR` pattern when you need custom tie behavior |
| Need the current filtered value after the filter changes | A `VAR` before `CALCULATE` |
| Need a value that responds to new filters | A measure reference inside `CALCULATE`, not a variable |
| Reading existing formulas that use `EARLIER` | Keep them working. Convert them to variables when you edit them |
Handling ties in the rank formula
The Price Rank formula uses a strict greater-than test, so products with the same price share a rank. If three products have the same highest price, all three get rank 1 and the next product gets rank 4. To break ties with a second column, extend the condition with another variable:
-- Calculated column in the Product table
Price Rank Unique =
VAR CurrentPrice = Product[Unit Price]
VAR CurrentName = Product[Product Name]
RETURN
COUNTROWS (
FILTER (
Product,
Product[Unit Price] > CurrentPrice
|| ( Product[Unit Price] = CurrentPrice
&& Product[Product Name] < CurrentName )
)
) + 1Among products with equal prices, the one whose name sorts first ranks higher. This assumes Product Name is unique. If it is not, ties remain.
Performance notes
- A nested iterator over two large tables evaluates its inner expression once per pair of rows. A ranking column over a table with 100,000 rows compares about 100,000 × 100,000 pairs. Calculated columns are computed at refresh time, so this cost appears as slow refresh.
- Putting a measure reference inside the inner iterator adds a context transition per row on top of that. Where possible, aggregate with a plain column expression, or reduce the inner table first.
- Computing a value once in a variable avoids repeating the same work several times in a formula.
Summary
- A same-table nested row context hides the outer row. A plain column reference reads the innermost row.
EARLIERreads the outer row. A variable defined before the inner iterator does the same job more clearly.- A variable is a fixed value computed where it is defined. It does not respond to filters added later.
Exercise
A calculated column on Product is written as COUNTROWS ( FILTER ( Product, Product[Unit Price] < Product[Unit Price] ) ) + 1. It is meant to rank products from cheapest (rank 1) upward, but every product shows 1. Why does this happen, and how do you fix it with a variable?
Show answer
Both Product[Unit Price] references resolve to the inner row context opened by FILTER, so each row is compared with itself and the condition is never true. COUNTROWS returns 0 and the rank is 1 for every product. Capture the outer price first: VAR CurrentPrice = Product[Unit Price] RETURN COUNTROWS ( FILTER ( Product, Product[Unit Price] < CurrentPrice ) ) + 1. The comparison then uses the outer product's price on the right, so a product's rank is one more than the number of cheaper products.
Exercise
A measure is written as VAR s = [Sales Amount] RETURN CALCULATE ( s, Product[Color] = "Blue" ). In a matrix with Product[Color] on rows, what does each row show, and how do you make the measure return blue sales?
Show answer
Each row shows the same value as [Sales Amount] for that row's color, and the Blue filter has no effect. The variable is computed before CALCULATE runs, so it is already a number when the filter is added. Move the measure into CALCULATE: CALCULATE ( [Sales Amount], Product[Color] = "Blue" ).