Sub topic 4
Calculated columns: new columns computed row by row
What this chapter assumes
This chapter assumes you can move around Power BI Desktop (Report, Table and Model views). It also assumes you know what a star-schema model looks like and can read basic DAX such as SUM, IF and column references. Row context, filter context and measures get their own chapters. Here they appear only as far as they explain how calculated columns behave.
What a calculated column is
A calculated column is a new column that you add to an existing table by writing a DAX expression. Power BI evaluates the expression once for every row of that table. It then stores the results in the model, next to the columns that came from the source.
After a refresh, a calculated column looks like any imported column. You can use it in a slicer, on a chart axis, in a filter, in a sort order or in a relationship. The model keeps no record of how a value was made, apart from the formula.
Here is the simplest case. The Sales table has Quantity and Unit Price. You want the amount for each order line.
Line Amount = Sales[Quantity] * Sales[Unit Price]You create it in Table view or Report view with New column. The part before = is the column name. The part after it is the expression.
How row context drives the calculation
When Power BI evaluates a calculated column, it works through the table one row at a time. For each row, the expression can see the values in that row. This is row context.
That is why Sales[Quantity] in the formula above returns a single number. It means "the Quantity in the row I am working on now". The formula contains no loop. The engine supplies the row.
The idea has two consequences:
- A bare column reference returns one value, the value in the current row.
- An aggregation such as
SUM(Sales[Quantity])inside a calculated column does not respect the current row. It adds up the whole column, because row context does not filter anything. Each row gets the same grand total.
The second point is a frequent source of confusion. This column looks plausible but does not do what a beginner expects:
Quantity Total = SUM(Sales[Quantity])Every row shows the same value, the total for the table. Row context lets you read the current row. It does not narrow an aggregation to that row.
Computed at refresh, stored in the model
A calculated column is evaluated at refresh time, not when a user opens a report or clicks a slicer. The results are written into the model's in-memory storage. Queries then read the stored values.
This has practical effects:
- Report interactions do not re-run the formula. The column is already there.
- The column adds to the model's size. Each value takes memory.
- The column adds to refresh time, because Power BI must calculate it again whenever the table is processed.
- The values are fixed until the next refresh. They do not react to slicer selections or to the filters on a visual.
That last point separates calculated columns from measures. A column holds a value that depends only on its own row, and on other tables reached through relationships. It cannot depend on what a user selected in the report.
Reading across relationships with RELATED
A calculated column can use values from a related table. In a star schema, each Sales row points to one Product row through a many-to-one relationship. RELATED follows that relationship from the current row and returns the value from the matching row on the "one" side.
Product Category = RELATED(Product[Category])This column belongs on the Sales table. For each sales row, Power BI finds the matching product and returns its Category.
Some details to keep in mind:
RELATEDworks from the "many" side toward the "one" side. To go the other way, from Product to its Sales rows, you needRELATEDTABLEor an aggregation, which later chapters cover.- It needs an active relationship. If the relationship is inactive or missing, the formula returns an error or fails to validate.
- It returns one value. That is guaranteed on the "one" side because the key is unique.
Calculated columns that make slicing fields
The strongest reason to write a calculated column is to produce a field that users can put on a slicer, a chart axis, a filter or a sort. Measures cannot do this. A measure returns a value computed from the current filters, so it has no fixed value per row to group by.
Price Band = IF(Product[List Price] >= 100, "High", "Standard")Put Price Band on an axis and Power BI groups products into two bars, High and Standard. A measure can then sum sales within each bar. This split between a column that classifies and a measure that aggregates is one of the most common patterns in DAX models.
Typical uses for a classifying column:
- Bands and buckets, such as age groups or price tiers.
- Flags, such as "Is Weekend" or "Is Overdue".
- Labels built from other columns, such as a display name from first and last name.
- Sort keys, such as a number column used with Sort by column so that month names appear in calendar order.
Where a calculated column is the wrong tool
A calculated column stores one value per row. That is a good fit for values that describe a row. It is a poor fit for values that must be combined across rows.
Ratios
Consider a margin percentage stored as a column.
Margin % (column) = DIVIDE(Sales[Profit], Sales[Line Amount])Each row now holds a correct margin for that row. Problems start when a visual summarizes the column. If you sum it, you get a number that is meaningless, such as 740%. If you average it, every row counts equally, so a small order has the same pull as a large one. Neither result equals total profit divided by total sales.
Say there are two rows. One has profit 10 on sales 100, a margin of 10%. The other has profit 90 on sales 100, a margin of 90%. The average of the column is 50%. The true margin is 100 / 200, which is 50%, so this case happens to agree. Change the second row to sales 900 with profit 90. The column average stays near 10% and 10%, giving 10%, and the true figure is 100 / 1000, which is also 10%. Now change the first row to sales 100 with profit 50, a 50% margin. The average of 50% and 10% is 30%, but the true margin is 140 / 1000, which is 14%. The average gives the wrong answer whenever row sizes differ.
The fix is a measure that divides the totals for whatever filters apply.
Margin % = DIVIDE(SUM(Sales[Profit]), SUM(Sales[Line Amount]))This is correct for one product, for a category and for the grand total. The next chapters on ratios return to this.
Aggregates that depend on the report
Anything that should change with a slicer, such as "sales for the selected year", cannot live in a calculated column. The column was fixed at refresh. Use a measure.
Compare with a measure that answers the same question
Suppose the business question is "What are total sales?" There are two routes. The first uses the calculated column from earlier and adds it up with a measure.
Total Sales = SUM(Sales[Line Amount])The second avoids the column and does the multiplication at query time.
Total Sales (no column) = SUMX(Sales, Sales[Quantity] * Sales[Unit Price])Both give the same number. The first stores a Line Amount value for every row in the model. The second stores nothing extra and calculates per row each time the measure runs. If nobody needs Line Amount as a slicing field, the second route saves memory and refresh time.
Changing the context from a measure
For comparison, a measure can change the filters it runs under. This line totals sales for red products only.
Red Sales = CALCULATE([Total Sales], Product[Color] = "Red")A calculated column has no equivalent behavior during refresh, because no report filters exist at that moment. Row context is the only context that applies, apart from relationships.
Costs and good habits
Each calculated column is stored, so large tables feel the cost most. A column with many distinct values, such as a per-row decimal, compresses poorly. A column with few distinct values, such as a two-value band, compresses well.
Habits that keep models healthy:
- Create a column only when you need the value on a slicer, axis, filter, sort or relationship.
- Prefer a measure when the result is an aggregate.
- Consider doing the work upstream. A column built in Power Query or in the source database is computed before the data reaches the model, and it can often be folded back to the source for faster refresh.
- Name columns clearly, and keep the formulas simple enough that others can read them.
Summary of behavior
| Property | Calculated column |
|---|---|
| Evaluated | At data refresh |
| Context | Row context, one row at a time |
| Stored in model | Yes, one value per row |
| Reacts to slicers | No |
| Usable on axis or slicer | Yes |
| Adds to model size | Yes |
Exercise
A Sales table has Quantity, Unit Price and Discount (a fraction such as 0.1). You add the column Net Price = Sales[Unit Price] * (1 - Sales[Discount]) and a second column Net % = DIVIDE(Sales[Net Price], Sales[Unit Price]). A colleague drops Net % into a table visual and sets it to Sum. Why is the total wrong, and what should replace Net %?
Show answer
Net % holds a per-row ratio, and summing ratios across rows has no meaning. Averaging it would also be wrong, because it gives small and large rows equal weight. Replace it with a measure that divides totals, such as DIVIDE(SUMX(Sales, Sales[Quantity] Sales[Net Price]), SUMX(Sales, Sales[Quantity] Sales[Unit Price])), which is correct at every level of the visual.
Exercise
You want to group customers by the Category of the product on each sales row, so you can show a slicer called Category on the Sales table. Write the calculated column, and say on which table it must be created and why.
Show answer
Product Category = RELATED(Product[Category]). Create it on the Sales table, the "many" side, because RELATED follows the many-to-one relationship from the current Sales row to its single matching Product row.