Sub topic 11
Pitfalls: duplicate rows, missing keys, and slow iterations
This chapter assumes you know the basics of filter context, row context, CALCULATE, and context transition from the earlier chapters. You should also be comfortable with one-to-many relationships and with the difference between a measure and a calculated column.
Context transition is powerful, but it fails quietly. The formula still returns a number, and the number is wrong or slow to compute. This chapter covers three problems: duplicate rows, missing keys, and expensive iterations.
What context transition really does
When a row context exists and a measure is evaluated (or CALCULATE runs), DAX turns the current row into a filter. It takes the value of every column of the row being iterated and applies each value as a filter on the same column. The filter then reaches other tables through relationships.
Two details matter for the pitfalls below:
- The filter is built from all the columns of the table being iterated, not only the key.
- If the table has a unique key column, the combined filter picks out exactly one row. If it does not, the filter can match several rows.
Pitfall 1: duplicate rows
Suppose a Customer table has no unique key. Two rows are identical in every column, perhaps because the same person was loaded twice.
| CustomerName | City | Segment |
|---|---|---|
| Ana Ruiz | Madrid | Retail |
| Ana Ruiz | Madrid | Retail |
| Ben Okafor | Lagos | Wholesale |
Now consider this measure from earlier in the tutorial:
Average Sales per Customer =
AVERAGEX ( Customer, [Sales Amount] )AVERAGEX opens a row context for each of the three rows. Context transition turns each row into the filter CustomerName = "Ana Ruiz", City = "Madrid", Segment = "Retail". Both Ana rows produce the same filter, so each of them sees all of Ana's sales. Her sales are counted twice in the average. The number is not an error, but it no longer means "average per customer."
Relationships make this worse. A relationship needs a column on the one side with unique values. If the join column is not unique, the model cannot create a one-to-many relationship on it. Many models then use a many-to-many relationship, or join on a non-unique column. In both cases, filters can reach more rows than intended.
How to detect it
Compare the row count of the table with the distinct count of its key. A quick check as a measure:
Duplicate Customer Rows =
COUNTROWS ( Customer ) - DISTINCTCOUNT ( Customer[CustomerKey] )A result above zero means that at least one key value appears more than once. A result of zero shows only that the key column is unique. It does not show that the key is the column the relationship uses.
How to fix it
- Remove duplicates upstream, in the source query or in Power Query, so that the dimension table has one row per entity.
- Add a unique key column and use it for the relationship.
- Where you cannot change the data, iterate over distinct values of the key instead of over the table:
Average Sales per Customer Key =
AVERAGEX ( VALUES ( Customer[CustomerKey] ), [Sales Amount] )Here the iterator runs over a single column. Context transition applies a filter on CustomerKey only, so each key is evaluated once, and every row with that key is still in the filter. Sales belong to the key, and each key is counted once.
Pitfall 2: missing keys
A fact table can contain a key value that has no match in the dimension table. For example, Sales[ProductKey] holds 999, but Product has no row with key 999.
DAX handles this with a blank row. When a relationship has an orphan value on the many side, DAX adds a blank row to the one-side table. Rows with unmatched keys belong to that blank row. You do not see it in the data view, but it appears in visuals as a blank group, and it is included in some functions and excluded from others.
Consider these two measures, both evaluated over Product:
Products Counted =
COUNTROWS ( Product )
Products Seen by Filters =
COUNTROWS ( VALUES ( Product[ProductKey] ) )Both count the blank row when the current filter context reaches it through the relationship, such as when a visual groups by a product column and orphan sales exist. The effects:
- A visual that groups by
Product[Category]shows a blank category with sales for key 999. The grand total is correct, but a reader may not know where the blank came from. - A measure that iterates
Productwith a measure reference does not reach the orphan sales, because the iteration covers real rows only (iterating the table in a row context does not include the blank row). The measure's total can then be lower than the total ofSales.
Sales via Product Rows =
SUMX ( Product, [Sales Amount] )Compare this with [Sales Amount] at the grand total. If the numbers differ, sales exist whose key has no product row. This difference is a useful data-quality test.
The related lookup behaves similarly. In a calculated column on Sales:
Product Category = RELATED ( Product[Category] )For a sales row with key 999, RELATED returns blank, because no product row exists. A later calculation that filters on Product Category = "Bikes" silently excludes those rows.
How to fix it
- Fix the data so that every fact key exists in the dimension, or add an explicit "Unknown" row to the dimension and map orphan keys to it.
- Test integrity with a measure that counts orphans:
Orphan Sales Rows =
COUNTROWS (
FILTER (
Sales,
ISBLANK ( RELATED ( Product[ProductKey] ) )
)
)A nonzero result tells you how many sales rows have no matching product.
Pitfall 3: slow iterations
An iterator runs its expression once per row. When that expression contains a measure reference, each row also triggers a context transition, and each transition runs a separate evaluation of the measure. Cost grows with the number of rows iterated times the cost of the measure.
Consider this calculated column on a large Sales table with millions of rows:
Customer Total Sales =
CALCULATE ( SUM ( Sales[Quantity] ) )It is correct, but it performs a context transition for every sales row, and the filter it builds covers all columns of Sales. Because Sales often has no unique key, rows that look alike may be merged by the filter. The result is slow and may be wrong.
Several habits reduce the cost.
Iterate over the smallest table that works
Compare these two measures:
Slow Products Over 1000 =
COUNTROWS (
FILTER ( Sales, [Sales Amount] > 1000 )
)
Fast Products Over 1000 =
COUNTROWS (
FILTER ( VALUES ( Product[ProductKey] ), [Sales Amount] > 1000 )
)The first iterates every sales row and tests a measure on each. The second iterates only the distinct products in the current filter context. Both use context transition, but the second does it far fewer times. Note that they also answer different questions: the first counts sales rows, the second counts products.
Avoid a measure inside an iterator when a column will do
If the expression is a simple calculation on columns, write it directly:
Sales Amount =
SUMX ( Sales, Sales[Quantity] * Sales[Unit Price] )This needs no context transition, because the row context already gives access to the columns. Wrapping it in a measure reference or CALCULATE adds a transition for no benefit.
Do not put context transition in a calculated column on a big table
A calculated column is computed once at refresh and stored. The cost is paid at refresh time and in memory. On a fact table, a measure reference in a calculated column triggers one transition per row. If the column can be a measure instead, make it a measure, because a measure is evaluated only for the cells shown.
Use variables to avoid repeated evaluation
A measure used twice inside an iterator is evaluated twice per row. Store it once:
Margin Flag Count =
COUNTROWS (
FILTER (
VALUES ( Product[ProductKey] ),
VAR Amount = [Sales Amount]
RETURN
Amount > 1000 && Amount < 50000
)
)The variable Amount is evaluated once for each product row inside the context created by the iterator, instead of once for each of the two comparisons.
Summary of cost factors
| Factor | Why it costs | What to do |
|---|---|---|
| Many iterated rows | One evaluation per row | Iterate a dimension key column, not a fact table |
| Measure reference in iterator | One transition per row | Use column expressions where possible |
| Wide tables | Transition builds a filter on every column | Iterate `VALUES` of one column |
| Repeated measure | Evaluated again each time | Store it in a variable |
| Calculated column on a fact table | Paid at refresh, stored in memory | Prefer a measure |
A checklist before you trust a transition
- Does the iterated table have a unique key, and does the relationship use it?
- Does every key in the fact table exist in the dimension table?
- Can you iterate
VALUESof a key column instead of the whole table? - Is a measure evaluated more than once per row? If so, put it in a variable.
- Does the grand total match the sum of the rows, and match a simple
SUMof the fact table?
Exercise
A Customer table has 1,000 rows but only 950 distinct values in Customer[CustomerKey]. Every other column is identical for the duplicated keys. You write AVERAGEX ( Customer, [Sales Amount] ). Why can the result be misleading, and how would you rewrite the measure without changing the data?
Show answer
For each of the 50 duplicated rows, context transition builds the same filter, so each copy sees the full sales of that customer and the sales are counted once per copy. The average is then computed over 1,000 rows instead of 950 customers and gives extra weight to duplicated customers. Rewrite it to iterate distinct keys: AVERAGEX ( VALUES ( Customer[CustomerKey] ), [Sales Amount] ). Each key is evaluated once.
Exercise
A visual shows total sales of 5,000,000 using [Sales Amount]. Another measure, SUMX ( Product, [Sales Amount] ), returns 4,800,000. What is the most likely cause, and which measure would you write to confirm it?
Show answer
Some Sales rows have a ProductKey that does not exist in Product, so those sales belong to the implicit blank row and are not reached when iterating the real Product rows. To confirm, count the orphan rows with COUNTROWS ( FILTER ( Sales, ISBLANK ( RELATED ( Product[ProductKey] ) ) ) ). A nonzero result confirms it. The lasting fix is to repair the keys or add an explicit Unknown product row.
Exercise
A measure does COUNTROWS ( FILTER ( Sales, [Sales Amount] > 1000 ) ) over a table with 20 million rows and is slow. Name two changes that reduce the cost.
Show answer
First, iterate a smaller set, such as VALUES ( Product[ProductKey] ), so there are far fewer context transitions (this changes the question from sales rows to products, so confirm that is what you want). Second, if the test can be written on columns of the row, drop the measure reference and use a column expression, which needs no transition. Storing a repeated measure in a variable also avoids evaluating it twice per row.