Power Pivot & DAX course · Lesson 13 of 16

Variables, DIVIDE and error handling in DAX

Write readable, fast and robust DAX with VAR and RETURN, safe division with DIVIDE, blank handling, SWITCH(TRUE()) and a growth measure that copes with gaps.

Advanced 20 min read

As measures grow, they become hard to read and easy to get wrong. A growth measure might evaluate last year's revenue three times; a margin measure might break with a division by zero when a slicer selects an empty month. This lesson covers the tools that make DAX robust and readable: variables with VAR and RETURN, safe division with DIVIDE, and the right way to deal with blanks and errors.

VAR and RETURN

A variable stores the result of an expression under a name, inside one measure. The pattern is: one or more VAR lines, then a single RETURN with the final expression.

DAX
Margin % :=
VAR Rev = [Revenue]
VAR Cost = SUMX ( Sales, Sales[Qty] * RELATED ( Products[Cost] ) )
RETURN
    DIVIDE ( Rev - Cost, Rev )
In the Measure dialog, line breaks are allowed: press Shift+Enter or just keep typing.

Variables bring three benefits:

  • Readability. Each step has a name, so the final expression reads like a sentence.
  • Speed. A variable is evaluated once, no matter how many times you use it. Without variables, [Revenue] might be computed twice or three times.
  • Debugging. Temporarily change RETURN to return one of the variables, check its value in the PivotTable, then switch back.
ABCD
1CategoryRevenueCostMargin %
2Accessories30012558.3%
3Computers4110300027.0%
4Displays56736036.5%
5Grand Total4977348530.0%

Margin % with variables, 2026 sales (lesson 12 data), Products[Category] on rows.

Variables are evaluated where they are defined

This rule catches everyone once. A variable is computed once, in the filter context where the VAR line is, and then it is a constant. CALCULATE cannot change it afterwards:

DAX
Wrong LY :=
VAR Rev = [Revenue]
RETURN
    CALCULATE ( Rev, SAMEPERIODLASTYEAR ( 'Calendar'[Date] ) )

Right LY :=
CALCULATE ( [Revenue], SAMEPERIODLASTYEAR ( 'Calendar'[Date] ) )
Wrong LY simply returns this year's revenue.

In Wrong LY, Rev already holds this year's number when CALCULATE runs, so shifting the dates has no effect. Put measures, not variables, inside CALCULATE when the filter context needs to change; or define the variable itself with CALCULATE: VAR PrevRev = CALCULATE ( [Revenue], SAMEPERIODLASTYEAR ( 'Calendar'[Date] ) ).

DIVIDE and division by zero

In Excel, dividing by zero gives #DIV/0!. DAX is different: the / operator does not raise an error. Dividing a number by zero (or by a blank, which counts as zero in arithmetic) returns Infinity, and 0 / 0 returns NaN (not a number). Both are useless in a report and break any chart that uses them.

DAX
DIVIDE ( <numerator>, <denominator>, [alternate_result] )
Returns alternate_result (blank by default) when the denominator is 0 or blank.

DIVIDE checks the denominator first and returns blank, or the value you supply as the third argument, when it is zero. Blank is usually the best choice, because the PivotTable then hides the row or leaves the cell empty. It is also faster than writing the check yourself with IF.

A robust growth measure

Growth must cope with three awkward cases: no sales last year (a new product), no sales this year (a discontinued product) and no sales in either. Using the two-year data from Time intelligence in DAX: TOTALYTD, SAMEPERIODLASTYEAR, DATEADD, DATESINPERIOD:

DAX
Revenue LY := CALCULATE ( [Revenue], SAMEPERIODLASTYEAR ( 'Calendar'[Date] ) )

Growth % :=
VAR Cur = [Revenue]
VAR Prev = [Revenue LY]
RETURN
    IF ( NOT ISBLANK ( Prev ), DIVIDE ( Cur - Prev, Prev ) )

Status :=
VAR Cur = [Revenue]
VAR Prev = [Revenue LY]
RETURN
    SWITCH (
        TRUE (),
        ISBLANK ( Prev ), "New",
        ISBLANK ( Cur ), "No sales",
        Cur >= Prev, "Up",
        "Down"
    )
Growth and a text status, each with two variables.
ABCDE
1ProductRevenueRevenue LYGrowth %Status
2Keyboard140-100.0%No sales
3Laptop285028500.0%Up
4Monitor56737850.0%Up
5Mouse30018066.7%Up
6Tablet1260New
7Grand Total4977354840.3%Up

Products[Product] on rows, Year slicer = 2026, months Jan–Apr. Growth % with 1 decimal.

Read it row by row. Keyboard sold 140 last year and nothing this year: growth is −100% and the status says so. Tablet is new: Prev is blank, so Growth % returns blank rather than Infinity, and the status says New. Laptop sold 2,850 in both periods, so its growth is exactly 0%. With a plain / the Tablet row would show an infinite value, and with DIVIDE alone it would also be blank, but the explicit ISBLANK test documents the intent for the next person who reads the measure.

SWITCH ( TRUE (), condition1, result1, condition2, result2, ..., else ) is the DAX way to write a chain of conditions without nesting IF inside IF. The first condition that is TRUE wins.

Blanks, zeros and errors

FunctionUse it for
BLANK ()Returning nothing on purpose, for example IF ( [Orders] < 3, BLANK (), [Avg Order] ).
ISBLANK ( value )Testing whether a measure or column value is blank.
COALESCE ( a, b, ... )First non-blank value, e.g. COALESCE ( [Revenue], 0 ). Available in current Microsoft 365 builds; elsewhere use IF with ISBLANK.
IFERROR ( value, alternate )Catching real errors such as a failed type conversion. Avoid it for divisions; DIVIDE is faster.
HASONEVALUE ( column )Checking that exactly one item is selected before showing a single-item result.

Arithmetic treats blank as zero (BLANK () + 5 is 5), but comparisons and functions sometimes keep it blank. ISBLANK is always the safe test. Be careful with = 0: in DAX, BLANK () = 0 is TRUE, so a check written as [Revenue] = 0 also catches blanks. Use == (strictly equal) in versions that support it if you need to tell them apart.

Watch out. Do not wrap every measure in IFERROR as a habit. It hides genuine mistakes (a wrong column, a text value in a number column) and it forces the engine to evaluate the expression in a slower, row-by-row way. Fix the cause and use DIVIDE for divisions.

Variables in calculated columns and complex logic

Variables work in calculated columns too, and they can hold tables, not just numbers. A common pattern is to keep a filtered table in a variable and count or sum it:

DAX
Repeat Customers :=
VAR CustomerList =
    FILTER ( VALUES ( Sales[CustomerID] ), CALCULATE ( COUNTROWS ( Sales ) ) >= 2 )
RETURN
    COUNTROWS ( CustomerList )
Number of customers with two or more order lines in the current context.

With the first Sales table of this course, Repeat Customers returns 4 at the grand total: Anna Weber and Brook Dental placed three orders each, Carter & Co and Delta Schools two each. Put Products[Category] on rows and the answer changes: in the Computers row only Anna Weber (orders 1001 and 1009) bought twice, so it returns 1. The inner CALCULATE makes COUNTROWS count each customer's own rows within the current category, through context transition.

Tip. Name variables after what they hold (Cur, Prev, CustomerList), keep RETURN on its own line and indent the final expression. Formatting tools such as DAX Formatter (daxformatter.com) produce a consistent layout you can paste back into the Measure dialog.

Check yourself

1. What does the / operator return in DAX when dividing 100 by 0?

2. Why does Wrong LY return this year's revenue?

3. What is the default result of DIVIDE ( 10, 0 )?

4. Which pattern replaces a long chain of nested IFs?

5. How often is a variable evaluated within one measure evaluation?