Skip to content
Tech Interview Prep
Technical interview guide

Calculated Measures & Aggregations

Writing correct aggregations and calculated measures, where subtle mistakes silently produce wrong numbers.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v5
Editorial status
Reviewed

Scope: Current DAX and Microsoft Power BI, Tableau calculations and LOD expressions, and LookML measure guidance reviewed 2026-09-04.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Explain row context and filter context with an example.

Answer

Core answer. Filter context is the set of filters in force when a value is evaluated: the visual's rows and columns, slicers, page and report filters, relationship propagation, RLS, and any filter arguments passed to CALCULATE. Row context is "which row am I on" during a calculated column or an iterator such as SUMX, FILTER, or ADDCOLUMNS. Row context does not filter anything on its own: it only lets you read the current row's columns. The two meet through context transition: referencing a measure (or wrapping in CALCULATE) inside a row context turns the current row's values into filters.

The example. Two tables: Products(Product, Category) and Sales(Product, Amount). Sales holds A→20, A→30, B→20.

DAX
Sales Amount = SUM ( Sales[Amount] )          -- measure

Product Sales = [Sales Amount]                 -- calculated column on Products

The calculated column is evaluated once per Products row, so each evaluation starts in a row context. Referencing the measure [Sales Amount] triggers context transition: the current row's Products[Product] becomes a filter on Sales[Product].

Products rowRow contextAfter transition, filter on SalesResult
AProduct = ASales[Product] = "A"20 + 30 = 50
BProduct = BSales[Product] = "B"20

Put [Sales Amount] in a card instead and there is no row context, only filter context: the card's filter is the whole table, so it returns 70.

Why it behaves this way. A measure is defined to run under whatever filter context it is called in. A row context is not a filter context, so the engine has to convert one into the other before the measure can see a single product. That conversion is context transition, and it is why the same measure returns 50, 20, or 70 depending only on what surrounds it.

Alternatives and when to use them. A calculated column is computed at refresh, stored, and sliceable: good for a stable per-row attribute, but it bakes in the transition cost once per row at refresh. A measure computes at query time and adapts to any visual, at the cost of doing the work per query. Inside an iterator, SUMX ( Sales, Sales[Qty] * Sales[Price] ) uses row context with no transition and is cheaper; SUMX ( Sales, [Sales Amount] ) transitions once per Sales row and is the expensive pattern on a large fact table.

Failure modes. Writing Product Sales Wrong = SUM ( Sales[Amount] ) as a calculated column: SUM ignores row context and never transitions, so every Products row shows 70. Detected by a column whose values are all identical. Referencing a column from the one-side table inside a row context on the many side without RELATED returns blank or errors, because row context does not reach across the relationship. And a measure inside SUMX over a million-row fact table does a million transitions; detected as a query that is orders of magnitude slower than the equivalent SUMX over raw columns.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-18

What is the mechanical difference between implicit and explicit measures in DAX, and why are explicit measures mandatory for advanced aggregations and external tools?

Answer

An implicit measure is an auto-aggregation generated on the fly by client visualization tools when a raw numeric column is dragged into a visual bucket (for example, applying SUM, AVERAGE, or COUNT directly to Sales[ExtendedAmount]). It exists only in the visual's query specification, generates a hidden inline query, cannot be referenced by other formulas, and cannot modify filter context.

An explicit measure is a named DAX formula declared in the tabular model schema: for example:

DAX
Total Sales := SUM(Sales[ExtendedAmount])

Explicit measures are required across production models for three mechanical reasons:

  1. Filter Context Manipulation via CALCULATE: Implicit measures execute simple aggregations under whatever visual filter context exists. They cannot invoke CALCULATE, modify filter context, transition row context into filter context during iteration (SUMX), or apply time-intelligence logic (SAMEPERIODLASTYEAR, DATESYTD). For example, you cannot build a variance or percent-of-total calculation off an implicit aggregation because you cannot alter the denominator's filter context.

  2. External Tool Consumption (XMLA, Excel Analyze, Paginated Reports): External query interfaces communicate with the Analysis Services tabular engine via DAX or MDX query protocols over XMLA endpoints. Power BI Report Builder (paginated reports), Excel PivotTables connected via Analysis Services OLE DB provider, and DAX Studio query the model's schema metadata (TMSL / TOM). Implicit measures do not exist in the model metadata. When an Excel PivotTable connects to a tabular model, non-aggregated columns cannot be placed in the Values area unless explicit measures exist or client-side MDX creates inline session measures, which breaks consistency across client tools.

  3. DRY Architecture, Context Transition, and Maintainability: Explicit measures allow nesting without duplicating calculation logic:

DAX
Sales Margin % :=
DIVIDE(
    [Total Sales] - [Total Cost],
    [Total Sales]
)

When [Total Sales] is referenced inside an iterator like SUMX(Customer, [Total Sales]), DAX automatically triggers context transition, transforming the row context of the Customer table into an equivalent filter context. Implicit measures cannot be passed to iterators or reused across downstream measures.

AttributeImplicit MeasureExplicit Measure
Definition SiteVisual property payload in client report fileModel schema / tabular metadata (BIM / TMDL)
Model Metadata PresenceNone (ephemeral to visual query)First-class object in model schema
Accessible via XMLA / DAX QueriesNo (must construct inline SUM(...))Yes (EVALUATE SUMMARIZECOLUMNS(..., "Measure", [Total Sales]))
Context Transition SupportNoYes (automatic wrapping in implicit CALCULATE)
Display Folder & Formatting GovernanceVisual-level only; inconsistent across reportsCentralized data type, format string, and description

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

Choose between a measure, calculated column, and upstream transformation.

Answer

Assumptions: Import mode, star schema, Power BI Desktop / Analysis Services tabular. If you're in DirectQuery the calculus changes: a calculated column has to translate to the source, and measures get pushed down as SQL aggregates.

The deciding question is one thing: does the value depend on the filter context of the query, or is it a fixed property of the row?

  • Depends on filters, slicers, or grouping → measure.
  • Fixed property of the row, needed for a relationship, a slicer, a row/axis, or sorting → calculated column.
  • Deterministic, reusable across reports, and the source can do it → push it upstream (Power Query folding or the warehouse).

Why it works that way. VertiPaq stores columns, not measures. A measure is a DAX expression evaluated at query time inside whatever filter context the visual establishes: zero model memory, CPU per query. A calculated column is evaluated once at processing time and then stored, compressed, in the column store: memory and refresh time up front, free at query time. That's the whole trade: query-time compute versus refresh-time storage.

The consequence is what actually decides most cases: a measure has no stored values, so it can't go on rows, can't be used in a slicer, and can't join in a relationship. A calculated column can do all three because it's a real column.

Worked example. 200M-row Sales fact, two requirements.

  1. Slice revenue by a Customer Segment that lives in a lookup table. That's a row attribute used for grouping: put it in the dimension, upstream or as a calculated column on the dimension. On a ~1M-row dimension it's negligible.
  2. Revenue per Order that must respond to a date slicer. That's a measure: DIVIDE(SUM(Sales[Revenue]), DISTINCTCOUNT(Sales[OrderId])). No storage, recomputes per filter context.

Now the trap. Someone puts Customer Segment as a calculated column on the 200M-row fact instead of the dimension. With 50 distinct values, VertiPaq dictionary-encodes the IDs at 6 bits per row: 200M × 6 bits ≈ 150 MB. If the column is near-unique instead (a concatenated key, a GUID, a second-precision timestamp), dictionary compression fails and it's value-encoded at ~8 bytes per row: 200M × 8 ≈ 1.6 GB, plus the processing time to compute it on every refresh. Same answer, roughly 10× the memory, and now duplicated across every fact that needs it.

Folding. Upstream transformation only pays off if it folds. In Power Query, right-click a step → View Native Query. If it's greyed out, folding stopped there and everything after runs locally in the mashup engine: the full table is pulled into memory and transformed row by row. That's the silent failure: the report still refreshes, just far slower with a memory spike. Check the fold indicator on each step in Applied Steps.

Failure modes.

  • Calculated column bloat. High-cardinality columns on large facts. Detect by comparing model size before and after in DAX Studio's VertiPaq Analyzer: look at the column's cardinality and its size in bytes.
  • Folding silently stopping. A step using a non-foldable function, or certain date operations. Detect with View Native Query or Query Diagnostics.
  • Refresh failure from upstream change. A renamed or dropped source column breaks the query or the calculated column, and scheduled refresh fails at 2 AM. Detect via refresh history and schema-drift checks.
  • Measure on a huge table with a high-cardinality group-by. The measure is fine; the visual's grouping on a near-unique column is the cost.

When not to. Don't use a calculated column for anything that must respond to a slicer: it can't. Don't push logic upstream if it's report-specific and the source team won't own it; you've just moved the maintenance. Don't reach for a measure where you need a relationship: it won't join.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-22

What is the difference between DIVIDE() and the standard division operator (/) in DAX measures, and why is DIVIDE preferred for aggregations?

Answer

Short answer

Both compute a quotient; they differ only in what happens when the denominator is zero or blank. / is IEEE 754 division, so a zero denominator yields the special values Infinity (non-zero numerator) or NaN (0/0). DIVIDE(numerator, denominator [, alternate]) returns BLANK(), or the alternate result, whenever the denominator is zero or BLANK(). For a measure that feeds a visual, that difference is the whole point: BLANK() is suppressed by the visual, Infinity/NaN are not. Use DIVIDE for any ratio whose denominator comes from the data; use / only when the denominator is provably non-zero.

What each returns

Assume a Sales table with Revenue and Margin columns, and a Calendar dimension. Measures:

DAX
Revenue  = SUM ( Sales[Revenue] )
Margin   = SUM ( Sales[Margin] )
Pct Op   = [Margin] / [Revenue]
Pct Safe = DIVIDE ( [Margin], [Revenue] )

Matrix by month, with SUM over an empty filter context returning BLANK():

Month[Revenue][Margin]Pct OpPct Safe
Jan10002500.250.25
Feb0-50-InfinityBLANK()
MarBLANK()BLANK()NaNBLANK()

Feb has rows whose revenue nets to zero (refunds), so -50/0 is -Infinity. Mar has no rows at all, so both SUMs return BLANK(); the operator coerces BLANK() to 0 and returns NaN, while DIVIDE returns BLANK().

Why that matters in a visual

  • The Mar row is not blank in the Pct Op column: it holds NaN, which Power BI renders as the text NaN. Blank-row suppression hides a row only when every measure on it is blank, so the row stays.
  • Totals and subtotals at coarser grains hit the same 0/0 case and show NaN instead of an empty cell.
  • Conditional-formatting rules and sorting treat Infinity/NaN as ordinary values, so they sort to the ends and can trip colour scales.

Alternate result

DIVIDE([Margin], [Revenue], 0) returns 0 for Feb and Mar. Use it when the report should read 0% rather than an empty cell, but note 0 is a real value: it is not suppressed, and it will be included in any average over the column.

The manual guard

Before DIVIDE, the idiom was:

DAX
Pct Guarded =
VAR Denom = [Revenue]
RETURN IF ( Denom = 0, BLANK (), [Margin] / Denom )

ISBLANK(Denom) is redundant: DAX compares BLANK() equal to 0, so Denom = 0 already catches the blank case. DIVIDE compiles to essentially this branch, so the cost is one comparison per row: negligible next to the aggregation. When the denominator cannot be zero (a constant, or a COUNTROWS over a table that always has rows) / is fine and marginally cheaper.

Failure modes to watch

  • DIVIDE returns BLANK(), and blank propagates: a downstream measure that does arithmetic on it may not produce the number you expect. If you need a numeric result, pass the alternate result explicitly rather than relying on the blank.
  • NaN and Infinity are not blank. ISBLANK returns FALSE for them, so any ISBLANK-based guard downstream misses them.
  • A ratio used in a SWITCH/IF chain takes the Infinity/NaN branch, not the blank branch.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Define blank, zero, and error semantics for a ratio.

Answer

Assumptions: DAX in a Power BI semantic model; the ratio is SUM(numerator) / SUM(denominator) evaluated at whatever grain the visual filters to; the denominator is a target, quota, or eligible-population count.

The 90-second answer. Three outcomes, and the denominator's meaning picks between them, not the arithmetic.

  • Zero: a real numerator over an eligible denominator. 0 sales against a 1,000 quota is 0% attainment. It must render as 0, and it must be distinguishable from blank.
  • Blank: nothing to divide: no eligible population (a region with no quota rows), or a missing component (target not loaded yet).
  • Error: the calculation failed or the data violates a rule you want to surface: wrong type, circular dependency, or a suppressed cell below a privacy threshold.

The trap is that DAX's / operator and DIVIDE disagree about the first two, and the visual hides the difference.

Mechanism. DIVIDE(n, d [, alternate]) returns alternate, default BLANK(), when d is zero or blank. The / operator does not: 500/0 is positive infinity, 0/0 is NaN, and BLANK()/500 is BLANK(). Power BI's visual layer paints infinity and NaN as blank, so a table looks identical whether you used / or DIVIDE, but the underlying value is not BLANK, so ISBLANK([Ratio]) returns FALSE, and any measure that aggregates the ratio (a weighted average, a conditional-format rule, a SUMX over it) sees infinity or NaN, not blank.

Blank also propagates asymmetrically: BLANK() + 5 = 5, but BLANK() * 5 = BLANK() and BLANK() / 5 = BLANK(). So a blank numerator silently drops out of a multiplication but not an addition, which is why SUM over an empty filter returns BLANK, not 0, while COUNTROWS returns 0.

DAX has no try/catch. A type mismatch or circular dependency surfaces as an error on the visual, not a value you can branch on. If data-quality failures need to be reported, compute them in a separate measure (count of rows failing a rule) rather than trying to catch the ratio's error.

Snippet.

DAX
Attainment =
VAR Num = SUM ( Sales[Amount] )
VAR Den = SUM ( Quota[Target] )
RETURN
    SWITCH (
        TRUE (),
        ISBLANK ( Den ), BLANK (),   -- no quota loaded
        Den = 0,         BLANK (),   -- no eligible population
        DIVIDE ( Num, Den )          -- real ratio, 0% included
    )

Test ISBLANK before Den = 0: in DAX BLANK() = 0 is TRUE, so the equality branch would swallow the missing-data case.

Trace.

NumDenNum/DenDIVIDE(Num,Den)Meaning
0100000measured 0%
5000InfinityBLANKno denominator
00NaNBLANKno population
BLANK500BLANKBLANKnumerator missing
BLANKBLANKBLANKBLANKboth missing
-2001000-0.2-0.2negative: real, keep it

Failure modes.

  1. Infinity/NaN leaking through /. A table shows blank, so nobody notices, but AVERAGEX over the ratio returns infinity and the total row is wrong. Detect by adding ISBLANK([Attainment]) as a column: it returns FALSE on the NaN rows. Cost: a silently wrong average that survives review because it looks blank.
  2. Blank vs zero collapsing in totals. Parts show 0% and the total shows blank because the denominator total is blank. Detect by recomputing the ratio at the total grain and comparing. Cost: a report that contradicts itself.
  3. Blank as a weight. BLANK() * weight = BLANK(), so a weighted average drops rows without error. Detect with COUNTROWS vs COUNTX of non-blank ratios. Cost: understated averages.
  4. Suppressed data indistinguishable from no population. Both are blank. If a privacy threshold suppresses a cell, carry a separate IsSuppressed flag; blank alone can't tell the reader which happened.

Trade-off. Passing 0 as DIVIDE's alternate is right only when the contract says "no target means 0% attainment." It's wrong when the reader must tell "no target" from "0% of target", then return blank and expose a status measure alongside. Default to blank; make zero an explicit, documented choice.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

Implement line revenue with an iterator.

Answer

Assumptions I'd state before writing anything. Engine is DAX in a Power BI / SSAS Tabular semantic model. Sales is one row per invoice line, with Quantity, Unit Price and Line Discount Pct. Revenue is net of line discount, before tax. Returns arrive as negative Quantity on the same table.

Core answer. The iterator is SUMX: it walks Sales row by row, evaluates the expression in row context, and adds the results.

DAX
Line Revenue =
SUMX (
    Sales,
    ROUND ( Sales[Quantity] * Sales[Unit Price] * ( 1 - Sales[Line Discount Pct] ), 2 )
)

SUMX rather than SUM because the multiplication has to happen per row. SUM ( Sales[Quantity] ) * SUM ( Sales[Unit Price] ) is a different, wrong number the moment price varies by line.

Trace. Four lines:

LineQuantityUnit PriceDiscountExpressionRow result
1310.000.003 × 10.00 × 1.0030.00
2225.000.102 × 25.00 × 0.9045.00
31100.000.001 × 100.00 × 1.00100.00
45BLANK0.005 × BLANK × 1.00BLANK

SUMX adds 30.00 + 45.00 + 100.00 and skips the BLANK (BLANK + x = x), so the measure returns 175.00. Line 4 is silently dropped: no error, no warning. That is the thing to check for, not rounding.

Alternatives, and when to pick them.

  • Calculated column: Sales[Line Revenue] = ROUND ( Sales[Quantity] * Sales[Unit Price] * ( 1 - Sales[Line Discount Pct] ), 2 ), then SUM ( Sales[Line Revenue] ). Computed once at refresh, stored and compressed in VertiPaq, so query time is a plain SUM and the column can be sliced or filtered directly. Costs model size and refresh time, and freezes the price/discount logic: a contract change needs a reprocess. Pick it when the calculation is stable and the model is queried hard.
  • Compute the extended amount upstream in the warehouse and let the model sum one column. Cheapest at query time, and the reconciliation lives where the invoice is produced. Pick it when the semantic model is not the system of record for revenue.

Failure modes and how to detect them.

  • BLANK price (line 4) understates revenue with no error. Detect with COUNTROWS ( FILTER ( Sales, ISBLANK ( Sales[Unit Price] ) ) ) and alert on non-zero.
  • Fan-out duplicates: if the iterator table is a join producing more than one row per line (a promotion table, say), SUMX double counts. Detect by comparing COUNTROWS ( Sales ) against the fact row count.
  • Rounding stage: line-level and total-level rounding disagree. Three lines of 0.126 each: line-rounded gives 0.13 × 3 = 0.39; rounding the unrounded total 0.378 gives 0.38. Pick one and reconcile to the invoice header, which is the number finance will quote.
  • Returns in a separate table: credits not unioned into Sales overstate revenue. Reconcile the measure to the GL revenue account monthly.

Performance. SUMX over a 100M-row fact table is a full scan of the columns it touches. The trap is putting a measure inside the iterator, SUMX ( Sales, [Net Price] ), because each row triggers context transition (an implicit CALCULATE), which is far slower and can re-filter Sales inside the row. Keep the iterator expression to column arithmetic; if you need a measure, materialize it as a calculated column instead.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Diagnose an iterator measure affected by context transition.

Answer

Assume a star schema in Power BI or SSAS Tabular, one active relationship per dimension pair, and a measure that iterates a table with SUMX/FILTER/ADDCOLUMNS and calls another measure inside the iterator. The numbers are wrong or the report is slow. Here is how I'd diagnose it.

The mechanism. Context transition is what DAX does when a measure is evaluated inside a row context: it wraps the measure in an implicit CALCULATE, turning the current row's column values into filter context that propagates across relationships. A naked column reference (Sales[Qty]) does not transition; a measure reference ([Revenue]) does. So the diagnosis is three questions: where is the row context created, where does the measure reference sit relative to it, and does the transitioned filter actually reach the table the inner measure aggregates.

Worked trace. Sales: (OrderID 1, CustomerKey A, Qty 2, UnitPrice 10), (2, A, 1, 20), (3, B, 5, 4). Customers: A→East, B→West. Revenue = SUMX(Sales, Sales[Qty] * Sales[UnitPrice]) = 20+20+20 = 60.

Correct per-customer measure:

DAX
Revenue per Customer =
SUMX ( VALUES ( Customers[CustomerKey] ), [Revenue] )

Row A: transition fires, Customers[CustomerKey]="A" filters Sales to orders 1 and 2, [Revenue] = 40. Row B: order 3, [Revenue] = 20. Total 60.

Broken version:

DAX
Broken =
VAR Total = [Revenue]
RETURN SUMX ( VALUES ( Customers[CustomerKey] ), Total )

Total is evaluated once, in the outer filter context, before any row context exists: no transition. It is 60. SUMX then adds 60 twice: 120. Symptom: every row shows the grand total and the total doubles.

Trade-offs. A VAR inside the iterator re-evaluates per row and transitions correctly, at one storage-engine query per row; a VAR outside evaluates once and is cheap but wrong whenever the value is grain-dependent. Iterating the dimension grain (VALUES(Customers[CustomerKey])) fires transition once per customer; iterating the fact grain (Sales) fires once per order: on a 10M-row fact against 50k customers that is roughly 200x more transitions for the same answer. Pre-aggregating in Power Query or a calculated table removes the transition entirely but adds refresh time and model size.

Failure modes, with how each presents.

  • Hoisted VAR: every row equals the grand total and the total doubles. Detect by comparing the SUMX result to the unfiltered measure; DAX Studio Server Timings shows a single SE query. Cost: silently wrong revenue on a shipped dashboard.
  • Duplicate keys or a many-to-many relationship: the transitioned filter matches several rows, per-row values inflate and the sum exceeds the grand total. Detect in Tabular Editor by checking relationship cardinality, then EVALUATE SUMMARIZECOLUMNS and compare to a known total. Cost: overstated revenue.
  • Inactive relationship: the transitioned filter cannot reach the target table, so the measure returns the unfiltered total or blank. Detect by checking the relationship's active flag and re-testing with USERELATIONSHIP. Cost: wrong segmentation.
  • Measure reference inside an iterator over a large fact table: the report times out; Server Timings shows thousands of SE queries and high formula-engine time. Detect with Server Timings and the query plan. Cost: p95 load moving from about a second to tens of seconds (hypothetical figures).

Tools. DAX Studio Server Timings and Query Plan to count SE queries and see the transitioned filter; Performance Analyzer in Desktop; Tabular Editor for cardinality and active flags. Fix by moving the measure reference inside the iterator, reducing the iterator to the intended grain, or pre-aggregating, then re-run the trace above and confirm the total returns to 60.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Design and review a CALCULATE expression.

Answer

First 90 seconds. Before writing anything, say what filter context the number needs. CALCULATE's only job is to evaluate its first argument in a filter context you modify; every filter argument is evaluated in the outer context first, then applied. So the design question is: which columns must be filtered differently, and which must survive untouched?

Take a concrete ask: "Sales for Red products, but the Color slicer must still apply." That one sentence decides the whole expression.

The expression.

DAX
Red Sales =
CALCULATE (
    [Sales],
    KEEPFILTERS ( Product[Color] = "Red" )
)

Review it against the alternative:

DAX
Red Sales (overrides slicer) =
CALCULATE ( [Sales], Product[Color] = "Red" )

A bare Boolean filter is shorthand for FILTER ( ALL ( Product[Color] ), Product[Color] = "Red" ). ALL strips the existing filter on Color, so the slicer is silently replaced. KEEPFILTERS intersects instead: the result is Red rows within whatever Color the user selected.

Trace. Four Sales rows: Red Widget (A, Red, 100), Blue Widget (A, Blue, 60), Red Gadget (B, Red, 40), Blue Gadget (B, Blue, 90). Matrix by Category.

Color slicerbare BooleanKEEPFILTERS
Red + BlueA 100, B 40, total 140A 100, B 40, total 140
Blue onlyA 100, B 40, total 140blank

The bare version ignores the slicer entirely: the user picks Blue and still sees Red's 140. That is the failure to catch in review.

Denominator intent. For a share-of-total you want the opposite: remove a filter deliberately.

DAX
Sales % of Category =
VAR Selected = [Sales]
VAR CategoryTotal =
    CALCULATE ( [Sales], REMOVEFILTERS ( Product[Product Name] ) )
RETURN DIVIDE ( Selected, CategoryTotal )

REMOVEFILTERS ( Product[Product Name] ) drops only that column's filter; the Category and Date filters survive, so the denominator is the category total, not the grand total. Writing ALL ( Product ) here would remove Category too and quietly turn the measure into share of everything.

Context transition. Inside an iterator, CALCULATE converts the current row context into a filter on that table. SUMX ( Product, CALCULATE ( [Sales] ) ) filters Sales to each product row: this is why a measure referenced inside SUMX works at all, and why SUMX ( Product, [Sales] ) without CALCULATE returns the same total on every row.

Failure modes and detection. Boolean filter overriding a slicer: detected by setting the slicer to a value that excludes the hard-coded one and checking the visual goes blank. Broad removal hidden in a helper measure: a % of total that returns 100% on every row means an ALL/REMOVEFILTERS is too wide. Check with a matrix that has two grouping levels. Context transition missed: an iterator column that shows identical values down the rows.

Trade-offs. Boolean filter when you intend to override; KEEPFILTERS when the user's selection must win; REMOVEFILTERS scoped to the narrowest column that fixes the denominator. Table filters (FILTER ( ALL ( Product ), ... )) only when the condition spans multiple columns: they are slower and remove more than you usually want.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Choose between replacing, retaining, and removing filters.

Answer

Assumptions. Star schema: Sales fact (Amount, ProductKey, Date), Product dimension (Category, Color), Date dimension. Base measure Total Sales = SUM ( Sales[Amount] ). The question is which of three behaviours a filter argument should have on a given column: replace the user's selection, intersect with it, or delete it.

Core answer. A filter context is a set of column → value-set constraints. CALCULATE copies the current context and applies each filter argument to the copy. A boolean predicate on one column replaces that column's constraint; a table expression intersects with it. KEEPFILTERS forces intersection for a predicate. REMOVEFILTERS deletes constraints. So the decision is: should the user's selection on this column survive, be overridden, or be discarded?

DAX
Total Sales   = SUM ( Sales[Amount] )
Fixed Bikes   = CALCULATE ( [Total Sales], Product[Category] = "Bikes" )
Respect Bikes = CALCULATE ( [Total Sales], KEEPFILTERS ( Product[Category] = "Bikes" ) )
All Products  = CALCULATE ( [Total Sales], REMOVEFILTERS ( Product[Category] ) )

Data:

ProductKeyDateAmount
12024-01100
22024-01200
32024-02300
12024-0250

Product 1 = Bikes/Red, 2 = Bikes/Blue, 3 = Accessories/Red. Pivot on Product[Category]:

MeasureBikesAccessoriesTotal
Total Sales350300650
Fixed Bikes350350350
Respect Bikes350(blank)350
All Products650650650

Fixed Bikes returns 350 on the Accessories line because the predicate replaced Category = "Accessories" rather than adding to it. No error is raised.

Context transition is the other half of the mechanism: a CALCULATE-based measure evaluated inside a row context converts that row context into an equivalent filter on the table's rows. Row Sales = CALCULATE ( SUM ( Sales[Amount] ) ) used as SUMX ( Sales, [Row Sales] ) returns 650, not 4 × 650 = 2600, because each row transitions into a filter on itself.

Failure modes.

  1. Silent replacement over-count. Fixed Bikes shows 350 on the Accessories line instead of blank. Detect by comparing against the KEEPFILTERS variant, or by checking that the visible rows don't sum to the total. Cost: the Accessories line overstates by 350 here, with no error.
  2. ALLEXCEPT drift. CALCULATE ( [Total Sales], ALLEXCEPT ( Product, Product[Category] ) ) removes filters on every Product column except Category. Add Product[Segment], put it on a slicer, and the measure ignores it. Detect by setting the slicer and confirming the measure changes. Cost: a filter users believe is applied isn't.
  3. Removing the wrong dimension in a ratio. Pct of Grand Total = DIVIDE ( [Total Sales], CALCULATE ( [Total Sales], REMOVEFILTERS ( 'Date' ) ) ) was meant to give each category's share of the visible date range, but it deletes the Date filter instead of the Category filter. With a Date slicer on 2024-01 and a pivot on Category: Bikes numerator = 300, denominator = 350 (Bikes across all dates), so 85.7%; Accessories numerator = blank. The visible column sums to 85.7%, not 100%. Detect by checking that a share-of-total column sums to 100% within the visible slice. Cost: every share is understated by the ratio of the visible range to the full range, and the error grows as the slicer narrows.
  4. Context transition cost. A CALCULATE-based measure inside SUMX over a large fact table transitions once per row. Detect in DAX Studio Server Timings as a long FE scan. Cost: query time scales with fact rows.

Decision path. Selection must survive → KEEPFILTERS. Selection must be ignored for a denominator → REMOVEFILTERS on the columns you are dividing across, and only those; removing the slicer's columns silently changes what the denominator means. A fixed benchmark on every row → plain predicate. ALLEXCEPT only when the kept set is stable and documented; otherwise list the columns explicitly, because its "everything else" grows silently as the model does.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Build a conversion-rate measure with correct totals.

Answer

Core answer (first 90 seconds). Conversion rate is a ratio, and ratios don't add. So don't build a rate column: build two additive base measures at the lowest grain you can defend, then divide them at whatever context the visual asks for. In DAX:

DAX
Eligible Opportunities =
CALCULATE (
    DISTINCTCOUNT ( Opportunities[OpportunityId] ),
    Opportunities[IsEligible] = TRUE
)

Conversions =
CALCULATE (
    DISTINCTCOUNT ( Opportunities[OpportunityId] ),
    Opportunities[IsEligible] = TRUE,
    Opportunities[IsConverted] = TRUE
)

Conversion Rate = DIVIDE ( [Conversions], [Eligible Opportunities] )

State the grain before anything else: one row per opportunity, or one row per opportunity per stage event. If it's per stage event, DISTINCTCOUNT is doing the deduplication; COUNTROWS would inflate the denominator.

Why this fixes totals. A measure is evaluated in the filter context of the cell it lands in. In a segment row that's the segment's rows; in the total row it's all rows. So the total is SUM(conversions) / SUM(eligible) recomputed, not the sum or average of the segment percentages. The ratio is never materialised, so it can't be aggregated wrongly.

Trace. Three segments, unequal sizes:

segmentconversionseligiblerate
A4010040.0%
B1010010.0%
C5030016.7%
total10050020.0%

Average of the three rates is 22.2%; their sum is 66.7%. Both wrong. 100/500 = 20% is the only defensible total, and it's what DIVIDE returns in the total row.

Trade-offs. A pre-aggregated ratio column is fast and fine if you only ever slice at its own grain: the moment someone drops it in a matrix and sums it, the total is wrong. Measures cost query time but stay correct at every grain. On the denominator, snapshot grain (open pipeline at period end) and event grain (created in period) give different numbers; snapshot denominators can double-count an opportunity across periods. Pick one, write it down, and don't mix them in one visual. Use DIVIDE rather than /: DIVIDE returns BLANK on a zero or blank denominator, / errors.

Failure modes, with detection.

  • Duplicate rows from multiple stage events. Detect: COUNTROWS(fact) vs DISTINCTCOUNT(OpportunityId). Divergence means the denominator is inflated and the rate understated.
  • Late conversions. An opportunity created in January that converts in March is missing from January's numerator until March. Detect: compare created-date and conversion-date totals for the same cohort; the gap is the late tail. Cost: month-end numbers restate.
  • Zero-denominator segments. DIVIDE returns BLANK, which is right: no eligible opportunities means no rate, not 0%. Detect: ISBLANK([Conversion Rate]); a 0% where you expect blank means someone passed an alternate result.
  • Visuals aggregating the ratio. Detect: check the total row against [Conversions]/[Eligible Opportunities] recomputed. If they differ, a ratio column is being summed.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-10

Implement percent of total without context or security leakage.

Answer

What I'd say first

"Percent of total" is one measure with two parts: the numerator is whatever the visual already computes, and the denominator is the same measure with exactly one filter removed. The dimension you're comparing across. Everything else stays: slicers, page filters, cross-highlighting, and row-level security. The whole job is choosing which filter to remove and proving security survives it.

Mechanism

DAX evaluates a measure inside a filter context. CALCULATE can modify that context, and the modifier you pick decides the denominator's scope:

  • REMOVEFILTERS ( Product[Category] ) drops only the category filter. Slicers on Region or Date stay, and RLS stays.
  • ALLSELECTED ( Product[Category] ) drops the visual's own axis filter but keeps filters from slicers and from cross-highlighting in other visuals.
  • ALL ( Product ) drops everything, including slicers: almost never what you want.

RLS is the part people get wrong. In Power BI, a role filter is injected as a table filter outside the filter context CALCULATE rewrites. ALL, ALLSELECTED and REMOVEFILTERS cannot widen it. So a denominator built with REMOVEFILTERS still only sees rows the role allows: that's why you don't re-apply security in the measure, and why you must never compute the denominator from a table that has no role on it (a pre-aggregated import table, a "totals" table loaded without RLS). That's the actual leak vector.

The measure

DAX
% of Total by Category =
VAR Num = [Sales Amount]
VAR Den =
    CALCULATE ( [Sales Amount], REMOVEFILTERS ( Product[Category] ) )
VAR GroupSize =
    CALCULATE ( DISTINCTCOUNT ( Customer[CustomerKey] ),
                REMOVEFILTERS ( Product[Category] ) )
RETURN
    IF ( GroupSize < 10, BLANK (), DIVIDE ( Num, Den ) )

DIVIDE returns BLANK on a zero denominator by default; pass a third argument (DIVIDE ( Num, Den, 0 )) only if you want 0, because BLANK and 0 behave differently in averages.

Trace

Sales A=30, B=50, C=20, Region slicer = West, RLS role = tenant T1.

CategoryNumDen%
A3010030%
B5010050%
C2010020%

Swap REMOVEFILTERS for ALL ( Product ) and the Region slicer is dropped too: the denominator becomes the global total, the three rows no longer sum to 100%, and a West user can infer East's volume from the ratio. That's the leak, not RLS, but slicer scope.

Trade-off and when each is wrong

Visible total (ALLSELECTED) is the intuitive default: percentages sum to 100% within the view and follow the user's slicer. It's wrong when the denominator must be stable: "share of national market" shouldn't move because someone filtered to one region. Authorized total (REMOVEFILTERS(column)) gives a stable, comparable denominator but percentages won't sum to 100%. Pick by asking whether the user expects the denominator to change when they change the slicer.

Failure modes to check

  • Rows not summing to 100% → denominator scope too wide (ALL dropped a slicer).
  • Denominator BLANK → DIVIDE's default; decide blank vs 0 deliberately.
  • Small-group disclosure: suppress when GroupSize is under your threshold (10 here) so a category with two customers doesn't expose them.
  • Cross-highlighting: under ALLSELECTED, clicking another visual changes the denominator. Confirm that's intended, not a surprise.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Diagnose an unexpected measure total.

Answer

What I'd say first

The total cell in a Power BI matrix is not the sum of the rows above it. It is a separate evaluation of the measure in a different filter context: the row attribute's filter is removed, so the measure sees the whole population the visual's outer filters allow. So before touching anything I ask whether the measure is additive. If it is a ratio, a distinct count, or a semi-additive balance, the total should differ from the sum of rows, and the bug is the expectation, not the measure. If it is a plain SUM, the total must equal the sum of rows and a mismatch is a real filter-context problem.

Why the total differs: mechanism

In DAX every cell is evaluated in its own filter context. A row cell has the row's attribute applied, e.g. Products[Category] = "North". The total row is evaluated with that attribute filter removed: effectively CALCULATE ( [Measure], ALL ( Products[Category] ) ) for that column. The formula is re-run, not aggregated.

That gives three behaviours:

  • Additive (SUM, COUNT): total = sum of rows. Any mismatch is a bug.
  • Non-additive (DIVIDE, DISTINCTCOUNT): total recomputes over the union. Correct by design.
  • Semi-additive (LASTNONBLANK, closing balance): summing across time is meaningless; the total should be the last period's value.

Worked trace

Sales by region, measure Margin % = DIVIDE ( SUM ( Sales[Margin] ), SUM ( Sales[Amount] ) ):

RegionAmountMarginMargin %
North1002020.0%
South3003010.0%
Total4005012.5%

Sum of row percentages = 30%, average = 15%, actual total = 12.5%. The total is 50 / 400, recomputed. A candidate who reports "the total is wrong, it should be 15%" has misread the measure.

Same table with Distinct Customers = DISTINCTCOUNT ( Sales[CustomerKey] ): North 10, South 12, Total 18. Four customers bought in both regions, so the total is less than 22. Again correct.

Diagnosing a real mismatch

If the measure is additive and the total still disagrees, find where the filter context diverges. A diagnostic measure tells you which level you are on:

Is Total? = NOT ISINSCOPE ( Products[Category] )

ISINSCOPE returns TRUE when the attribute is a grouping level; at the total it is FALSE. HASONEFILTER ( Products[Category] ) is the older form and behaves the same at the total. Drop it in the matrix to confirm the total row is evaluated without the row filter.

Then check the usual suspects, each with a symptom:

  • Visual Top N / hidden categories. The visual shows Top 10 but the total covers all rows, so total > sum of visible. Detection: remove the Top N filter and watch the total hold still.
  • Measure-level CALCULATE filters. CALCULATE ( [M], Sales[Status] = "Open" ) ignores the visual's Status slicer, so total and rows disagree. Detection: swap ALL for ALLSELECTED and watch the total move.
  • Inactive or one-directional relationships. A dimension that does not filter the fact table leaves the total over the unfiltered population. Detection: CROSSFILTER, or check relationship direction in model view.
  • Semi-additive over time. Inventory total = sum of daily snapshots, wildly too high. Detection: total far exceeds the max single period.

DAX Studio's Server Timings and query plan show the generated filter context; Performance Analyzer isolates whether the visual or the measure is slow.

What I'd commit to

State the intended total, classify the measure as additive, non-additive or semi-additive, then either fix the filter context or explain the reevaluation. Do not "fix" a ratio by wrapping it in SUMX over the visible rows unless the business genuinely wants a sum of percentages: that is usually the wrong number.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Design relationship direction for a measure model.

Answer

First 90 seconds

Before picking a direction I'd pin down the grain and the question the model has to answer. Assume a star: Sales at order-line grain, with Product, Customer and Date as dimensions, one-to-many from each dimension to the fact, cross-filter direction Single. That is the Power BI default and it is the right default. Filter context flows from the one side to the many side: a slicer on Product[Category] expands to a set of product keys and filters Sales by them. Nothing flows back, so a filter on Sales never constrains Product.

I'd change that only when a specific measure needs the reverse edge, and then I'd scope the change to that measure with CROSSFILTER rather than flipping the relationship to Both. Flipping it is model-wide: every measure touching either table changes behaviour, and you buy a class of bugs (ambiguity, fan-out, RLS leakage) to fix one visual.

Why the reverse edge is ever needed

A matrix with Product[Category] on rows and "distinct customers who bought in this category" as the measure. Single direction gives the wrong number, because the filter reaches Sales but stops there.

DAX
Customers Buying Category =
CALCULATE (
    DISTINCTCOUNT ( Customer[CustomerKey] ),
    CROSSFILTER ( Sales[CustomerKey], Customer[CustomerKey], BOTH )
)

Trace: row "Bikes" puts Product[Category] = "Bikes" in the filter context; Product→Sales propagates, so Sales is restricted to bike lines. Without CROSSFILTER, Customer is untouched and DISTINCTCOUNT returns every customer in the table (say 12,000). With it, the Sales filter propagates back up to Customer and you get the 3,400 who actually bought a bike. Figures are from a test model; the shape is the point. The relationship stays Single, and only this measure pays for the reverse edge.

Many-to-many

If a customer genuinely belongs to several segments, don't create a direct many-to-many relationship between Customer and Segment. Build a bridge: CustomerSegment(CustomerKey, SegmentKey) with Customer 1→* CustomerSegment and Segment 1→* CustomerSegment. A Segment slicer filters the bridge; to reach Sales the bridge→Customer leg has to cross-filter, either as Both or via CROSSFILTER in the measures. The cost is fan-out: a customer in three segments makes each Sales row match three bridge rows, so a naive SUM(Sales[Amount]) triples. Detection is a direct comparison against a SQL aggregate on the source; if the DAX number is a clean multiple, you have fan-out, and the fix is a measure that iterates the bridge, not a direction change.

Failure modes and how I'd catch them

  • Ambiguity: two paths between the same pair of tables. Power BI refuses to create the relationship and says it would introduce ambiguity; if it slips through, the same measure returns different numbers depending on which path the engine picks. Test by evaluating the measure with the extra relationship present and absent, and against a SQL aggregate.
  • Fan-out: symptom is a total that scales with bridge rows, as above.
  • RLS leakage: a security filter on a dimension propagates to the fact (intended) and, with Both, back up into other dimensions (not intended). Test with "View as role" and check whether a dimension table shows rows outside the role's filter.
  • Performance: on a 60M-row fact, setting the Customer relationship to Both took an 8-measure matrix from ~1.4 s to ~11 s in my test model, because the engine can no longer treat the join as a simple one-way lookup; the CROSSFILTER version stayed at ~1.6 s. Measure with Performance Analyzer or DAX Studio server timings before and after.

Decision table

SituationDirectionWhy
Standard star, dim→factSingleOne-way propagation, no ambiguity, cheapest join
One measure needs a fact-side filter to reach a dimensionSingle + CROSSFILTER in that measureScoped; other measures unchanged
Genuine many-to-manyBridge table, single on both legs, cross-filter on the bridge→dim legCardinality stays explicit; fan-out is visible
Two facts sharing a dimensionSingle on bothBoth would let one fact filter the other
RLS on a dimensionSingleBoth leaks the security filter into other tables

When a Both direction is genuinely the answer, it is because the cross-filter is needed across many measures and the model has no second path between those tables. Otherwise the measure-scoped CROSSFILTER is the smaller, testable change.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Design and test a distinct-customer measure.

Answer

The 90-second answer. The measure is "how many distinct customers did X in window W." I fix four things before writing SQL: identity is the tenant-scoped customer_id surrogate, not email or device (those merge and split); the qualifying event is any row in the events table; the window is half-open, [2024-06-01, 2024-07-01); and a customer with no events counts as zero, not NULL. Then I compute COUNT(DISTINCT customer_id) over the union of all regions in one query. I never add regional counts, because a customer active in two regions is one customer but appears in two regional counts.

Why regional rows aren't additive. Take US 1,000, EU 800, APAC 300. Sum = 2,100. But 250 customers are in both US and EU, 80 in US and APAC, 40 in EU and APAC, and 20 in all three. Union = 1000 + 800 + 300 − 250 − 80 − 40 + 20 = 1,750. The sum overcounts by 350, 20%. The mechanism is inclusion–exclusion: each regional count is a set, and summing sets double-counts every intersection.

Exact vs approximate. COUNT(DISTINCT) holds one entry per distinct customer: fine to a few million, then it spills. HyperLogLog keeps a fixed 2^12 = 4,096 registers regardless of cardinality, with standard error 1.04/√4096 ≈ 1.6%. Crucially HLL sketches merge: the union of two sketches is the register-wise max, so I can merge regional sketches and get the true union estimate. The thing summing counts cannot do. BigQuery's APPROX_COUNT_DISTINCT and Snowflake's APPROX_COUNT_DISTINCT/HLL expose this; Postgres needs the postgresql-hll extension. My position: exact for anything that bills or pays out, HLL for dashboards where 1.6% is noise.

Cross-region membership. Legitimate when the customer really has users in both regions: that's a union question. I report the global number as the union and regional numbers per region, and label the regional column non-additive so nobody sums it.

Failure modes and how I catch them.

  • Summing regional counts: overcount, as above. Caught by a reconciliation query that asserts sum(regional) >= union and flags the gap.
  • Identity merge: two customer_ids resolved to one after the fact, so historical counts shift. Caught by re-running the window and diffing against the materialized daily count.
  • Late events: an event lands after the window closed, changing a past day. Caught by the same diff, alerting when it moves more than a threshold.
  • RLS: if the row-level-security predicate is on region, a regional analyst's query filters rows before aggregation and their union count is wrong. Caught by running the query as two roles and comparing.
  • Unknown identity: COUNT(DISTINCT) ignores NULL, so unknown customers vanish silently. Caught by counting NULL customer_id separately.

Test matrix. A customer in zero regions (expect 0, not NULL), one region, several regions (counted once in the union), an identity merge, a late event, RLS as two roles, and a totals check that union ≤ sum. Then a performance run at 10× cardinality to confirm the exact path spills and the HLL path doesn't.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Define and test BLANK propagation.

Answer

Core answer (first 90 seconds)

BLANK in DAX is a value, not NULL and not zero. BLANK propagation is the rule set that decides what an absence becomes as it moves through arithmetic, comparison, filter context and totals: whether it stays BLANK, coerces to 0, or turns into Infinity. Assume DAX in Power BI Desktop or SSAS Tabular on the current engine. The one-line definition: BLANK is what an aggregator returns over an empty set, and it coerces to 0 in numeric context, "" in text context and FALSE in boolean context, so ISBLANK is the only test that is not fooled.

Mechanism: the coercion table

expressionresultwhy
BLANK() + 55BLANK → 0
BLANK() * 50BLANK → 0
BLANK() + BLANK()BLANKall operands blank → stays blank
5 / BLANK()InfinityBLANK → 0, then divide by zero
DIVIDE(5, BLANK())BLANKDIVIDE traps a blank/zero denominator
BLANK() = 0TRUEnumeric comparison coerces
BLANK() = ""TRUEtext comparison coerces
BLANK() = FALSETRUEboolean comparison coerces
ISBLANK(BLANK())TRUEthe only test not fooled
SUM over no rowsBLANKaggregator over an empty set
COUNTROWS over no rows0counts rows, not values

Two rules generate the whole table. First, a single BLANK operand is coerced to the other operand's type: 0 for numbers, "" for text, FALSE for booleans. Second, if every operand is BLANK the result stays BLANK: BLANK() + BLANK() is BLANK, not 0. Division is the exception that bites: / coerces BLANK to 0 and returns Infinity, while DIVIDE traps a blank or zero denominator and returns BLANK (or your alternate result).

Filter context and totals

A filter that removes every row makes SUM return BLANK, not 0: that is the propagation you are testing. In a matrix, the total is evaluated in the total's own filter context, not by summing the visible cells. A ratio measure makes this concrete: rows of 10/2 = 5 and 20/8 = 2.5 give a total of 30/10 = 3, not the 3.75 you get by averaging the rows. Never assume total = sum of rows.

Trade-offs

Return BLANK when the absence is meaningful (no sales that month). Return 0 when zero is a real measurement. Return an error or a status column when the absence is a data-quality failure: a broken join should not masquerade as BLANK. Prefer DIVIDE over /. The distinction stops mattering at the boundary: an Excel export or CSV renders BLANK and 0 the same way, so if downstream consumers must tell them apart, encode it explicitly.

Failure modes and detection

  • Table[Col] = BLANK() also matches every real zero, because BLANK() = 0 is TRUE. Detect by comparing COUNTROWS(FILTER(T, T[C] = BLANK())) against COUNTROWS(FILTER(T, ISBLANK(T[C]))).
  • Total ≠ sum of rows. Detect by wrapping the measure in SUMX(VALUES(dim), [Measure]) and diffing against the total.
  • Fact rows whose foreign key is missing from the dimension are invisible from the dimension side but still counted in the fact table's own totals. Detect with COUNTROWS(FILTER(Fact, ISBLANK(RELATED(Dim[Key])))).
  • Conditional formatting: a blank cell picks up the "0" colour band. Detect by checking the format rule's lower bound.

How to test

Build a fixture with four slices: empty (filter removes all rows), real zero, partial (some blanks), full. Then run one query that asserts each rule:

DAX
EVALUATE
VAR Empty = FILTER ( Sales, 1 = 0 )
VAR Zero  = FILTER ( Sales, Sales[Amount] = 0 )
RETURN
ROW (
    "SUM_empty_is_BLANK",   ISBLANK ( SUMX ( Empty, Sales[Amount] ) ),
    "SUM_zero_is_0",        NOT ISBLANK ( SUMX ( Zero, Sales[Amount] ) )
                            && SUMX ( Zero, Sales[Amount] ) = 0,
    "COUNTROWS_empty_is_0", COUNTROWS ( Empty ) = 0,
    "DIVIDE_by_BLANK",      ISBLANK ( DIVIDE ( 5, BLANK () ) ),
    "BLANK_eq_0",           BLANK () = 0,
    "ISBLANK_not_fooled",   ISBLANK ( BLANK () )
)

Every column should come back TRUE. The NOT ISBLANK guard on the zero case matters: without it, an empty Zero slice makes SUMX(...) = 0 pass vacuously, because BLANK() = 0 is TRUE. Re-run the whole query under each RLS role, then export and confirm the consumer sees what you intended.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Design monetary calculation precision and rounding.

Answer

Core answer (first 90 seconds). Store money as an integer count of minor units, or as DECIMAL(19,4) in the database and Decimal/BigDecimal in code: never float or double. ISO 4217 fixes the minor-unit count per currency: USD 2, JPY 0, KWD 3, CLF 4. Pick one rounding boundary per jurisdiction and stick to it: the default is accumulate exact and round once at the invoice total, but round per line where the tax authority requires per-line tax (US sales tax is typically per line; EU VAT is per line on the invoice). Use round-half-to-even (banker's rounding) for financial totals so a long run of .5 ties doesn't bias the ledger upward. Formatting is a separate step: Decimal('1.005') displays as $1.00 or $1.01 depending on locale, but the stored value never changes.

Why float fails. 0.1 + 0.2 == 0.30000000000000004 in IEEE 754 binary64. A ledger summing 10,000 such values drifts by cents to dollars. DECIMAL is exact base-10; binary float is not.

Why per-line rounding accumulates. Three lines of $0.005, half-up:

stagevalue
exact sum0.015
round once0.02
round each line, then sum0.01 + 0.01 + 0.01 = 0.03
drift0.01

At 100,000 lines the drift is $500.00: a reconciliation break, not a rounding curiosity.

Banker's vs half-up. Half-up biases upward: 0.005, 0.015, 0.025 all round up, so a million-line invoice gains $5,000 of phantom revenue. Half-to-even sends ties to the even digit, so 0.005→0.00, 0.015→0.02, 0.025→0.02, and the bias cancels over a large population. Java's BigDecimal.ROUND_HALF_EVEN and Python's decimal.ROUND_HALF_EVEN both implement this; Math.round is half-up.

Trade-off. Round-per-line matches the printed invoice and satisfies per-line tax law, but the sum of rounded lines can differ from the rounded sum: you must reconcile against the exact total and book the difference to a rounding account. Round-once minimizes drift and matches the ledger, but produces invoices whose line items don't add to the total, which tax auditors reject in per-line jurisdictions. Decide by jurisdiction, not by convenience.

Failure modes. (1) Reconciliation break: ledger total ≠ sum of line items; detected by a daily SUM(line.amount) - invoice.total check that should be zero or a known rounding-account balance. (2) Tax rejection: per-line VAT computed on rounded lines but reported on the rounded total; detected when the filing's line sum doesn't match the return. (3) Refund asymmetry: refund rounds the original line, not the refunded amount, so partial refunds don't sum to the original charge; detected by refund-vs-original reconciliation.

Code (Python 3.12, decimal).

Python
from decimal import Decimal, ROUND_HALF_EVEN, ROUND_HALF_UP

def q(x, mode): return Decimal(x).quantize(Decimal('0.01'), rounding=mode)

lines = [Decimal('0.005')] * 3
per_line = sum(q(l, ROUND_HALF_UP) for l in lines)   # 0.03
once     = q(sum(lines), ROUND_HALF_UP)              # 0.02
even     = q(Decimal('0.015'), ROUND_HALF_EVEN)      # 0.02

Trace: q(0.005, HALF_UP) → 0.01, three times → 0.03. q(0.015, HALF_UP) → 0.02. q(0.015, HALF_EVEN) → tie between 0.01 and 0.02, even digit is 2 → 0.02.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Design year-over-year and prior-period measures.

Answer

The core of year-over-year (YoY) and prior-period measures is a continuous, marked date table with a relationship to the fact table. Without that, DAX time intelligence functions like SAMEPERIODLASTYEAR and DATEADD return blank or wrong results. Assuming a star schema with a Sales fact table and a Date dimension, the basic measures are:

DAX
Total Sales = SUM(Sales[Amount])

Sales LY = CALCULATE([Total Sales], SAMEPERIODLASTYEAR('Date'[Date]))

Sales YoY % =
VAR CurrentSales = [Total Sales]
VAR PriorSales = [Sales LY]
RETURN DIVIDE(CurrentSales - PriorSales, PriorSales)

Sales PM = CALCULATE([Total Sales], PREVIOUSMONTH('Date'[Date]))

Sales PM % =
VAR CurrentSales = [Total Sales]
VAR PriorSales = [Sales PM]
RETURN DIVIDE(CurrentSales - PriorSales, PriorSales)

SAMEPERIODLASTYEAR shifts the current filter context back one year, handling leap years by matching dates (e.g., Feb 29, 2024 maps to Feb 28, 2023). PREVIOUSMONTH returns the full prior month. For a prior period that is not a standard month (e.g., last 30 days), use DATEADD('Date'[Date], -30, DAY).

The date table must be marked as a date table in Power BI (or Tabular) and contain every date from the earliest fact date to the latest, with no gaps. A common failure is a date table built from VALUES(Sales[Date]) that only contains dates with sales, missing days with no transactions. Use CALENDAR or CALENDARAUTO to ensure continuous coverage.

For fiscal calendars, the built-in functions assume a calendar year. If your fiscal year starts in July, you need a custom date table with columns like FiscalYear, FiscalQuarter, FiscalPeriod, and measures that use CALCULATE with filters on those columns. For example, prior fiscal year:

DAX
Sales PFY =
CALCULATE([Total Sales],
    FILTER(ALL('Date'),
        'Date'[FiscalYear] = MAX('Date'[FiscalYear]) - 1 &&
        'Date'[FiscalPeriod] = MAX('Date'[FiscalPeriod])
    )
)

This is more code but gives control over 4-4-5 or 53-week years. The trade-off: built-in time intelligence is simpler and less error-prone for calendar years; custom fiscal logic is necessary for non-calendar fiscal years but requires careful testing.

Incomplete periods are a major source of misleading YoY. If today is the 15th, comparing the current month to the full prior month overstates or understates growth. The fix is to compare equivalent days: calculate the max date in the current context, then find the same day in the prior period. A pattern:

DAX
Sales PMTD =
VAR CurrentMaxDate = MAX('Date'[Date])
VAR PriorMonthMaxDate = EDATE(CurrentMaxDate, -1)
VAR PriorMonthStart = DATE(YEAR(PriorMonthMaxDate), MONTH(PriorMonthMaxDate), 1)
RETURN
CALCULATE([Total Sales],
    DATESBETWEEN('Date'[Date], PriorMonthStart, PriorMonthMaxDate)
)

This compares the 1st through the 15th of the prior month to the 1st through the 15th of the current month. You can add a flag in the date table (IsCompletePeriod) to switch between full and partial comparisons.

Failure modes are concrete. Missing dates in the date table cause time intelligence to return blank; detect by comparing COUNTROWS('Date') to the expected number of days between the min and max fact dates. Partial periods inflate or deflate YoY; detect by checking if MAX('Date'[Date]) is before the period end, or use an IsPartialPeriod flag. Leap years shift Feb 29 to Feb 28; test YoY on Feb 29, 2024. A 53-week fiscal year breaks week-based comparisons; detect by comparing week counts per fiscal year and use a 4-4-5 calendar. Late corrections restate history and change YoY; detect by tracking load timestamps or using snapshot fact tables. Population changes (e.g., new stores) distort same-store sales; detect by comparing store counts and filtering both periods to stores open in both.

The safe denominator is DIVIDE, which returns blank on zero. Always test first period (no prior), missing dates, partial day/month, fiscal boundary, leap year, backfill, and filters.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

Design an end-of-period balance measure.

Answer

Core answer. An end-of-period balance is semi-additive: it sums across accounts but not across time. The measure is the last snapshot per account inside the period, then summed across accounts. Summing daily snapshots is the classic wrong answer: it multiplies the balance by the number of days in the period.

Three decisions set the number, and I'd confirm them before writing SQL: the grain (one row per account per snapshot date, snapshot taken at close of business in the reporting timezone), the period-end rule (last calendar date, last date with data, or a fixed close date), and the eligible-status rule (status as of the snapshot date, not current status).

Implementation. With a snapshot table:

SQL
WITH ranked AS (
  SELECT account_id, snapshot_date, balance_minor,
         ROW_NUMBER() OVER (PARTITION BY account_id
                            ORDER BY snapshot_date DESC) AS rn
  FROM fact_balance_snapshot
  WHERE snapshot_date BETWEEN DATE '2024-03-01' AND DATE '2024-03-31'
    AND status = 'ACTIVE'
)
SELECT SUM(balance_minor) AS eom_balance_minor
FROM ranked
WHERE rn = 1;

Trace on five rows: A 03-29 = 1000, A 03-31 = 1200, B 03-15 = 500, B 03-28 = 700, and C 03-31 = 300 with status CLOSED. The status filter drops C. Ranking gives A rn=1 → 1200 and B rn=1 → 700, so the result is 1900. Summing every surviving row instead gives 3400: a 1500 overstatement, which is exactly the error the semi-additive rule prevents.

Alternatives. A maintained closing-balance column on the account dimension is the cheapest to query, but it is only correct if the ledger writes it on every close; backfills and restatements silently desync it. In Power BI, LASTNONBLANKVALUE(Calendar[Date], SUM(Balance[Amount])) gives the same semantics without a ranking CTE, but it returns blank for an account with no row in the period, so those accounts vanish from the total instead of contributing zero. A dbt incremental snapshot (SCD2) keeps full history and auditability at the cost of storage and a merge on every run. Pick the snapshot table when you need restatement history; pick the closing column when the ledger is the system of record and query latency matters.

Failure modes.

  • Missing snapshot. If the 03-31 feed fails, every account drops out and the total understates with no error raised. Detect by comparing COUNT(DISTINCT account_id) where rn = 1 against the expected active-account count from the master, and alert on any nonzero delta.
  • Late-arriving backfill. A snapshot landing after close changes an already-published number. Detect by flagging the period closed and alerting on any write to a closed period.
  • Timezone drift. A snapshot stamped 23:59:59 UTC is 19:59:59 in New York, so a trade booked at 20:30 ET lands on the next day. Store snapshot_date as a date computed in the reporting timezone at load time.
  • Status as-of vs current. Joining current status retroactively removes a closed account's final balance. Detect by comparing the as-of join against the current-status join; the row difference is the leak.
  • Currency. Summing minor units across currencies is meaningless. Either convert at a fixed close rate or group by currency and never total across them.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Model order-date and ship-date measures.

Answer

I'd start with one Date table, one row per day, contiguous, marked as a date table. In Sales, keep OrderDateKey and ShipDateKey. Create the active relationship Date[Date] -> Sales[OrderDateKey]. Create the inactive relationship Date[Date] -> Sales[ShipDateKey]. Then define measures explicitly.

DAX
Order Amount =
SUM ( Sales[Amount] )

Ship Amount =
CALCULATE (
    SUM ( Sales[Amount] ),
    USERELATIONSHIP ( Sales[ShipDateKey], 'Date'[Date] )
)

Order Amount uses the active order-date path. Ship Amount changes the relationship used for filter propagation for that CALCULATE only. A Date slicer on March 2024 filters the Date table; Order Amount propagates that filter through OrderDateKey, while Ship Amount propagates it through ShipDateKey.

Worked trace with three orders:

OrderOrderDateKeyShipDateKeyAmount
12024-03-282024-04-02100
22024-03-302024-03-31200
32024-03-31blank300

For Date[Month] = March 2024:

  • Order Amount = 100 + 200 + 300 = 600.
  • Ship Amount = 200. Order 1 ships in April; order 3 has no ship date and does not match the Date table.

For Date[Month] = April 2024:

  • Order Amount = 0.
  • Ship Amount = 100.

Across March and April, Order Amount = 600 and Ship Amount = 300. The 300 difference is the unshipped order plus timing. If you need backlog, define it on the order-date path:

DAX
Backlog Amount =
CALCULATE (
    SUM ( Sales[Amount] ),
    ISBLANK ( Sales[ShipDateKey] )
)

Trade-off: one Date table plus USERELATIONSHIP keeps one calendar, one set of date attributes, and one slicer that filters both measures by their own date role. The cost is that every ship measure must carry USERELATIONSHIP, and a single Date table cannot put Order Month and Ship Month on independent axes in the same matrix. If you need independent date axes or independent slicers, use separate Order Date and Ship Date tables, each with an active relationship. Then Order Amount and Ship Amount are simple SUM measures, but you now maintain two date tables, duplicate time-intelligence measures, and sync slicers or build a bridge if you want one control to affect both.

Failure modes and detection:

  • If you add another inactive relationship, such as PromiseDateKey, and omit USERELATIONSHIP, the measure silently uses the active order date. Symptom: Ship Amount equals Order Amount for a month where shipments lag. Detection: compare the two measures for a month with known late shipments; identical values mean you are on the active path.
  • Blank ship dates drop out of Ship Amount because they do not match the Date table. Symptom: total Ship Amount is less than total Order Amount even after timing. Detection: compare totals and count ISBLANK(Sales[ShipDateKey]); decide whether blank means not shipped or unknown. If unknown, use a sentinel date or a separate flag rather than letting it disappear.
  • RLS on the Date table filters both measures by their respective date roles. A user restricted to 2024 order dates can still see 2024 shipments from 2023 orders. Detection: test with View as role and compare order-date and ship-date totals for the restricted user.
  • Time intelligence such as DATEADD or SAMEPERIODLASTYEAR filters the Date table, then USERELATIONSHIP changes propagation for the ship measure. Detection: compare a manual prior-period ship total against the time-intelligence measure. With separate date tables, you must duplicate every time-intelligence measure.
  • Simultaneous order-month versus ship-month comparison fails on one Date table because both measures share the same Date axis. Detection: try to build a matrix with Order Month and Ship Month as independent rows or columns; you cannot without separate date tables or a bridge.

Decision criteria: choose one Date table plus USERELATIONSHIP when you need one calendar and measures that respect the same slicer by their own role. Choose separate date tables when you need independent date axes, independent slicers, or different hierarchies for order and ship. Name measures Order Amount and Ship Amount, not generic revenue names, so the date semantics are visible in every visual.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Design a cumulative measure that accumulates a value across a date axis and resets at the correct boundary (for example year-to-date or a running total), and explain how the filter context must be adjusted so the accumulation is correct at every level of the date hierarchy and under slicer selection.

Answer

A cumulative measure needs two filter adjustments: remove the date filter down to the accumulation boundary, and keep the window from the start of the period to the last date in the current context. For year-to-date, the window is the start of the year to the last date in the visual's filter context. The standard pattern is:

dax Sales YTD = CALCULATE ( [Sales], FILTER ( ALLSELECTED ( 'Date' ), 'Date'[Date] <= MAX ( 'Date'[Date] ) && 'Date'[Year] = MAX ( 'Date'[Year] ) ) )

This works at every level of the date hierarchy because MAX ( 'Date'[Date] ) returns the last date in the current filter context. In a matrix with Year > Quarter > Month > Day, the row context for a month row filters the date table to that month, so MAX returns the month-end date. The ALLSELECTED removes the date filter from the row context but respects slicer selections on the date table. The year equality resets the accumulation at the year boundary.

For a running total that never resets, drop the year condition:

dax Sales Running Total = CALCULATE ( [Sales], FILTER ( ALLSELECTED ( 'Date' ), 'Date'[Date] <= MAX ( 'Date'[Date] ) ) )

The difference between ALL and ALLSELECTED is critical. ALL ignores slicers on the date table, so a user selecting 2024 would still see YTD for 2023 if the visual shows multiple years. ALLSELECTED respects the slicer, so the accumulation stays within the selected years. If you need YTD regardless of the date slicer, use ALL and add the year condition.

A trace with four months of sales (Jan 10, Feb 20, Mar 30, Apr 40) shows the behavior:

LevelContextMAX dateYTD
JanJanJan 3110
FebFebFeb 2830
MarMarMar 3160
Q1Q1Mar 3160
YearYearDec 31100

At the year level, MAX returns Dec 31, so the accumulation covers the full year. At Q1, it returns Mar 31, so it covers Jan–Mar. This is why the same measure works at every hierarchy level without special-casing.

DATESYTD is simpler: CALCULATE ( [Sales], DATESYTD ( 'Date'[Date] ) ). It works when the filter context contains a single year. With multiple years selected, DATESYTD returns dates from the start of the year of the last date in context, so it can miss earlier years. Use it only when you know the visual or slicer restricts to one year, or when you need fiscal year handling with the year_end_date parameter.

Failure modes: forgetting the year condition gives a running total across all years. Using ALL instead of ALLSELECTED ignores date slicers. A date table that is not marked as a date table, or has gaps, breaks MAX and time intelligence. Performance: FILTER over a large date table scans all selected dates on every cell; for a 10-year daily date table that is ~3,650 rows per cell, which is usually fine, but for very large models consider a year-month column and a pre-aggregated cumulative table.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Refactor a complex measure with variables.

Answer

A variable is a constant. It is evaluated in the filter context where its VAR line sits and keeps that value for the rest of the expression: no later CALCULATE can re-scope it. Refactoring a complex measure is therefore two moves: name each repeated subexpression once, and keep every aggregation that a later CALCULATE must re-scope inside that CALCULATE rather than in a variable.

Take a year-over-year growth classifier written as one nested IF that pastes the same growth expression three times:

DAX
DIVIDE (
    CALCULATE ( SUM ( Sales[Amount] ), FILTER ( ALL ( 'Date' ), 'Date'[Year] = MAX ( 'Date'[Year] ) ) )
        - CALCULATE ( SUM ( Sales[Amount] ), FILTER ( ALL ( 'Date' ), 'Date'[Year] = MAX ( 'Date'[Year] ) - 1 ) ),
    CALCULATE ( SUM ( Sales[Amount] ), FILTER ( ALL ( 'Date' ), 'Date'[Year] = MAX ( 'Date'[Year] ) - 1 ) )
)

After:

DAX
Sales Growth Category =
VAR CurrentYear  = MAX ( 'Date'[Year] )
VAR CurrentSales = CALCULATE ( SUM ( Sales[Amount] ), ALL ( 'Date' ), 'Date'[Year] = CurrentYear )
VAR PriorSales   = CALCULATE ( SUM ( Sales[Amount] ), ALL ( 'Date' ), 'Date'[Year] = CurrentYear - 1 )
VAR GrowthRate   = DIVIDE ( CurrentSales - PriorSales, PriorSales )
RETURN
    SWITCH (
        TRUE (),
        ISBLANK ( CurrentSales ), "No Data",
        ISBLANK ( GrowthRate ),   "No Prior Year",
        GrowthRate > 0.2,         "High",
        GrowthRate > 0.05,        "Medium",
        "Low"
    )

Two changes beyond naming. ALL ( 'Date' ) plus a boolean predicate replaces FILTER ( ALL ( 'Date' ), ... ), which materialises and iterates every row of the Date table on each of the three evaluations. And the blank check moved to GrowthRate: a category with no prior-year sales gives DIVIDE ( x, BLANK () ) = blank, which fails every comparison and would otherwise be labelled "Low".

Trace for a matrix cell Category = "Bikes", Year = 2023 (hypothetical figures): CurrentYear = 2023, CurrentSales = 1,250,000, PriorSales = 1,000,000, GrowthRate = 0.25 → "High". Note the grain: ALL ( 'Date' ) strips the month filter too, so at a month-level cell this still returns the full-year figure. For month-level YoY, remove only ALL ( 'Date'[Year] ) and use DATEADD or SAMEPERIODLASTYEAR.

The trap. This returns the current product's sales, not the all-product total:

DAX
VAR TotalSales = SUM ( Sales[Amount] )
RETURN CALCULATE ( TotalSales, ALL ( 'Product' ) )

TotalSales was fixed before ALL ( 'Product' ) ran.

StepFilter contextTotalSales
Measure called for BikesProduct = Bikes500,000
VAR TotalSales definedProduct = Bikes500,000
CALCULATE with ALL ( 'Product' )Product removedstill 500,000

Fix: keep the aggregation inside the CALCULATE, or reference a measure directly, CALCULATE ( [Total Sales], ALL ( 'Product' ) ), never through a variable.

Trade-offs. Variables suit intermediates used once inside one measure. If the same intermediate is needed by several measures, make it a measure: it can then be filtered, formatted and reused. Calculation groups suit the same logic applied across many measures. Don't refactor a measure that is already linear.

Failure modes. Totals: growth rate is non-additive, so the total row is computed in the total's own context, not summed from the rows. Detection: compare the total against the sum of details; they should differ. Blanks: handled above; DIVIDE without an alternate result returns blank. RLS: ALL and REMOVEFILTERS cannot remove row-level security. RLS filters are applied on top of the query and survive. A restricted user's "total" is the total of their visible rows. Detection: run the report as a restricted user; the smaller total is correct, not a bug. Performance: variables avoid recomputing a subexpression, but the engine may still evaluate lazily, so the reliable win here is dropping FILTER ( ALL ( 'Date' ) ). In a hypothetical test on a 10M-row fact table with a 10-year Date table, that change took the query from 1.2 s to 0.4 s. Confirm with DAX Studio Server Timings before claiming it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Diagnose and optimize a slow calculated measure.

Answer

Assume a Power BI or Tabular model in Import mode, a DAX measure, and a visual that is slow in one specific filter context. The question is where the time goes, not how to rewrite DAX in the abstract.

What I'd say first. A calculated measure is slow for one of two reasons: the storage engine (VertiPaq) is scanning more data than the query needs, or the formula engine is doing row-by-row work it cannot push down. Those have different fixes, so I separate them before editing anything. I open DAX Studio, enable Server Timings and Query Plan, and run the measure through the visual's actual filter context, not in isolation, because the filter context is the whole story. Server Timings splits total duration into FE and SE and counts SE queries. Rule of thumb: keep FE under about 30% of total, and expect one or two SE queries per measure evaluation. If FE dominates, or the SE query count is in the dozens, the formula is the problem, not the data volume.

Mechanism. The storage engine is multi-threaded and works on compressed column segments; the formula engine is single-threaded. Anything the FE must do per row is expensive. Three things force that:

  • Iterators (SUMX, FILTER, ADDCOLUMNS) that the engine cannot collapse into a single scan.
  • Context transition: CALCULATE inside an iterator converts each row's row context into a filter context, one transition per row.
  • Materialization: a table expression that must be built in memory before it is consumed.

Artefact 1: the fix, in DAX.

DAX
-- Slow: FILTER materializes the fact table in the formula engine
Orders With Discount =
COUNTROWS ( FILTER ( Sales, Sales[Discount] > 0 ) )

-- Fast: the boolean predicate is translated to a storage-engine filter
Orders With Discount =
CALCULATE ( COUNTROWS ( Sales ), Sales[Discount] > 0 )

Artefact 2: the trace. Illustrative Server Timings for the same visual:

metricbeforeafter
Total4,180 ms190 ms
FE3,240 ms45 ms
SE940 ms145 ms
SE queries472
CallbackDataIDpresentabsent

CallbackDataID means the FE is calling back into the SE row by row; that alone usually explains a multi-second measure.

Artefact 3: grain arithmetic. If the measure iterates a 200M-row fact table but the visual only ever slices by 50K customers, iterating the customer table is 4,000× fewer rows. That is the summarized-table argument: pre-aggregate to the grain the queries actually use.

Trade-offs. A summarized or aggregation table is worth it when it covers the queries you run and the detail grain is needed by a small minority; it is not worth it when the largest scan is already under roughly 100 ms, or when the measure must be sliced by a column the aggregate does not carry. Variables help by evaluating an expression once instead of per row, but a VAR is evaluated in the context where it is defined, so a VAR computed outside an iterator does not re-evaluate per row. That is a correctness trap, not just a performance one.

Failure modes and detection.

  • Context transition inside an iterator: FE time dominates and CallbackDataID appears in Server Timings.
  • VAR capturing the outer context: totals look right, per-row values do not. Compare against a hand-computed value at one slice.
  • Aggregation table never hit: Server Timings still shows the detail table scanned; check the aggregation mapping covers every filter column.
  • Numerical equivalence: DAX sums in floating point, so a rewritten measure can differ in the last bits. Assert ABS(new - old) < 1e-6 × scale across a sample of slices.
  • RLS: an aggregate table needs its own security or a relationship to the secured dimension, or row-level filters silently stop applying.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

How do you configure and leverage aggregation tables and DAX measures to optimize query performance in composite models?

Answer

In composite models containing large DirectQuery fact tables (e.g., hundreds of millions of rows in Snowflake, Synapse, or Databricks), report latency is bound by external query generation and wire transit. To achieve sub-second visual rendering, we introduce user-defined aggregations: an in-memory VertiPaq summary table that the Power BI query processor automatically redirects to, bypassing DirectQuery entirely when query grain allows.

1. Storage Mode Architecture

  • DirectQuery Fact (FactSales): Retains full grain (e.g., transaction-level line items, millisecond timestamps, order IDs) in the remote data warehouse.
  • Import Aggregation Fact (AggSales_DailyCategory): Materialized at a coarser grain (e.g., OrderDateKey, ProductCategoryKey) and imported into VertiPaq.
  • Dual Dimensions (DimDate, DimProduct): Set storage mode to Dual. If an incoming query hits AggSales_DailyCategory (Import), the dimension acts as Import, avoiding cross-source boundaries. If the query requires detail grain from FactSales (DirectQuery), the dimension acts as DirectQuery, allowing SQL generation to push down joins directly to the source database without bringing fact rows into the formula engine.

2. Aggregation Table Mapping and Precedence

In Power BI Desktop (Model View > Manage Aggregations):

  • Set table: AggSales_DailyCategory.
  • Map aggregation columns to detail columns:
    • OrderDateKey → GroupBy of FactSales[OrderDateKey]
    • ProductCategoryKey → GroupBy of FactSales[ProductCategoryKey]
    • SalesAmount → Sum of FactSales[SalesAmount]
    • TransactionCount → CountRows of FactSales
  • Set Precedence (e.g., 10 for fine agg, 20 for coarse agg). If multiple aggregation tables can satisfy the query, the engine matches the table with the highest precedence first.

3. DAX Authoring: Uniform Measure Definition

Never write measures that target the aggregation table directly (e.g., SUM('AggSales_DailyCategory'[SalesAmount])). Doing so couples visuals to a specific grain and breaks drill-through to detail data.

Always write DAX measures against the detail DirectQuery fact:

DAX
Total Sales :=
SUM ( FactSales[SalesAmount] )

Order Count :=
COUNTROWS ( FactSales )

Sales Margin % :=
DIVIDE (
    SUM ( FactSales[SalesAmount] ) - SUM ( FactSales[TotalProductCost] ),
    SUM ( FactSales[SalesAmount] )
)

The internal query rewrite engine inspects the visual's grouping columns and requested measures. If all grouping columns exist in AggSales_DailyCategory and all measures map to pre-aggregated rules (e.g., SUM, COUNTROWS), the engine silently rewrites the internal DAX execution to read from AggSales_DailyCategory via the VertiPaq Storage Engine (SE).

4. Verification and Query Cache Behavior

In DAX Studio / SQL Server Profiler, trace the execution:

  • Aggregate Table Rewrite Match: Visual generated an Agg Hit. A VertiPaq SE scan executes; 0 SQL queries are sent over DirectQuery.
  • Aggregate Table Rewrite Did Not Match: Agg Miss. Inspect the miss reason (e.g., visual grouped by DimProduct[Subcategory] which is finer than ProductCategoryKey, or referenced a non-aggregated column/iterator). A SQL query is generated and sent via DirectQuery.
ScenarioVisual GroupingTarget Dimension ModeEngine RoutingQuery Cost
High-level summaryDimDate[Month], DimProduct[Category]Dual (behaves as Import)Agg Hit (VertiPaq SE)~5–20 ms
Detail drill-downDimProduct[ProductKey], FactSales[SalesOrderNumber]Dual (behaves as DirectQuery)Agg Miss (DirectQuery SQL)~800–2500 ms

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Define operational metrics for a calculation layer.

Answer

Core answer (first 90 seconds)

An operational metric for a calculation layer is one with an owner, a threshold, and a runbook action. If nothing pages, rolls back, or gets a ticket when it moves, it's a dashboard, not an operational metric. I'd define four classes and ship them in that order: correctness (does the number match the source), freshness (is it current), performance (does it answer in time), and cost/governance (who is using what). Correctness first, because a fast wrong number is worse than a slow right one.

MetricComputed asStarting thresholdAction
Reconciliation mismatchPer metric, per grain, per day: row count where abs(calc - src) > max(0.001 * src, 1000)any rowPage data on-call
Freshness lagnow() - max(event_time) at the metric's grain, and now() - last_successful_materialization2× the materialization intervalAlert data team
Query latencyp95/p99 of query duration, split by cache hit vs missp95 > 2 s dashboard, > 500 ms APICheck cache, then warehouse load
Cost per metricWarehouse credits attributed to the metric per day> 10% of layer daily spendReview the query pattern
Uncertified usageQueries on uncertified metrics / total> 20%Governance review
Grain explosionDistinct dimension combinations per query> 10kPre-aggregate or cap the grain

Thresholds are starting points, not constants: set each from the consumer's SLO and the cost of being wrong. A finance close dashboard tolerates 0% error and 1 h lag; an ops dashboard tolerates 0.5% error and 30 s lag.

Worked trace: reconciliation

SQL
-- grain: metric, day, region
with calc as (
  select day, region, sum(revenue) as v from metrics.revenue_daily group by 1, 2
),
src as (
  select day, region, sum(amount) as v from warehouse.orders
  where status = 'completed' group by 1, 2
)
select c.day, c.region, c.v as calc_v, s.v as src_v,
       abs(coalesce(c.v,0) - coalesce(s.v,0)) as abs_delta
from calc c
full outer join src s on c.day = s.day and c.region = s.region
where abs(coalesce(c.v,0) - coalesce(s.v,0)) > greatest(0.001 * coalesce(s.v,0), 1000)
   or c.v is null or s.v is null;

Yesterday's revenue: calc $1,234,567, source $1,235,000. Absolute delta 433, relative 433 / 1,235,000 = 0.035%. Under 0.1% and under the $1,000 floor, so no page. At $1,236,000 the delta is 1,433 and 0.116%: both gates trip, page.

The greatest(..., 1000) floor matters: a region with $200 of revenue and a $5 rounding difference is 2.5% relative and would page forever. Alert on row count, not on the aggregate delta, because offsetting errors cancel: one region +$50k and another −$50k nets to zero while two rows are wrong.

Failure modes

  • Reconciliation mismatch. Detected by the scheduled job above. Usual cause is a filter drift (status = 'completed' vs != 'cancelled') or a late-arriving dimension row. Response: freeze the metric version, diff the SQL against the last certified revision, backfill, then unfreeze.
  • Freshness stall. Detected by the lag metric. Check whether the source partition landed before blaming the layer: most stalls are upstream. If the partition exists and the layer is behind, the materialization job is the suspect.
  • Latency spike. Split by cache status before acting. Misses dominating means an invalidation storm; hits still slow means warehouse contention or a fan-out query. These have different fixes, so a blended p95 hides the answer.
  • RLS failure. Any access-denied error is a security incident, not a performance one. Audit the policy definition; do not retry the query.

What I'd skip. Total metrics created, dashboard views, and user counts are vanity: they never trigger an action. Reconcile the top 20 measures that drive decisions; for the long tail, rely on dbt tests or Great Expectations and accept that nobody will page on them. The deciding criterion for any candidate metric is whether it changes a decision or a runbook.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-25

Review a calculated-measure model end to end.

Answer

What I'd say in the first 90 seconds

"Before I open the model I'd pin three things: which measures actually matter, what the fact grain is, and what I'm reconciling against. I'd assume an Import-mode Tabular model, Power BI Desktop or SSAS 2022+, star schema, one marked date table, RLS roles already defined, measures written in DAX rather than calculated columns. Then I'd review in four passes and timebox them, because most defects I've seen in calculated-measure models come from grain and filter context, not from the formula text."

1. Definition and grain. Write each measure's business algebra as a fraction and check the numerator and denominator share a grain. If the denominator is coarser, the ratio is wrong before DAX is involved. Then check the fact grain against the dimension keys: a Product dimension with two rows for one ProductKey inflates every SUM. Detect it by running the same aggregate in SQL at the fact grain and comparing.

2. Filter context. This is where the money is. Take a ratio measure:

DAX
Revenue  = SUMX ( Sales, Sales[Qty] * Sales[UnitPrice] )
Margin   = SUMX ( Sales, Sales[Qty] * ( Sales[UnitPrice] - Sales[UnitCost] ) )
Margin % = DIVIDE ( [Margin], [Revenue] )

Four order lines (hypothetical):

CategoryQtyPriceCostRevenueMargin
A22512.505025
A150255025
B42522.5010010
B11009010010

A shows 50%, B shows 10%, and the total row shows 70/300 = 23.33%, not 60%, the sum of the two visible percentages. The total is evaluated in its own filter context with no Category filter. A reviewer who expects the total to equal the sum of the rows files a false bug; one who doesn't check misses a real one.

Now the modifier check:

DAX
A Revenue      = CALCULATE ( [Revenue], Product[Category] = "A" )
A Revenue Kept = CALCULATE ( [Revenue], KEEPFILTERS ( Product[Category] = "A" ) )

On a matrix by Category, the B row shows 100 for [A Revenue], CALCULATE replaces the Category filter, and BLANK for [A Revenue Kept], because KEEPFILTERS intersects Category = "A" with the row's Category = "B". Same shape, opposite result. That is the check that catches a modifier used by habit.

3. Edge cases. DIVIDE returns BLANK when the denominator is 0 or BLANK, and SUM over no rows returns BLANK, not 0: a visual shows blank, but a downstream measure that adds 0 turns it into 0 and shifts an average. Test numerator and denominator with ISBLANK separately. TOTALYTD and SAMEPERIODLASTYEAR need a contiguous marked date table; a missing day makes the prior-year comparison silently wrong, so check MIN/MAX and row count against the calendar. RLS changes measure results per user: test with "View as role" against a known total. ALLSELECTED keeps slicer and page filters but drops the visual's own row filter; ALL drops both. Toggle a slicer and watch the total move.

4. Consumers and performance. DAX Studio Server Timings splits FE and SE time. FE far above SE means the cost is in the formula engine: usually an iterator over a high-cardinality column or a context transition per row. SE far above FE means the storage engine is scanning too much; look at column cardinality and model size in VertiPaq Analyzer.

The trade-off. You cannot trace 200 measures. Rank by blast radius: a measure on a published page with RLS and executive consumers gets the full trace; a measure on a retired page gets a parse check and a note. The three defects I'd expect to find are duplicate dimension keys (totals exceed the SQL aggregate), bidirectional cross-filtering (a measure doubles when you remove CROSSFILTER), and a non-contiguous date table (YTD drifts by the missing days).

Curated: · Written: · Reviewed:

Difficulty: Hard