The easiest way to start using variables in #dax

A few months ago, I and Alberto realized that the reason why variables are not used in DAX as they should is that… there are not many examples out there!

For this reason, we made a commitment to use them more often in our example. We didn’t do that in 2015 and 2016 because of the larger number of Excel 2010/2013 and SSAS 2012/2014 users, but in 2017 most DAX users work in Power BI, and variables are available also in Excel 2016 and SSAS Tabular 2016. There are no more excuses.

You will see the result of this effort soon (we have been working on content that will be published in the next months), and might have already noticed we use variables often in our articles on SQLBI.

If you still wonder why you should use variable and how to start… well, I have a very good example. Consider the following code that sums only the positive balance available for each customer.

Positive Balances :=
SUMX (
    Customer, 
    IF (
        [Balance] > 0,
        [Balance]
    )
)

The code above works and provides the correct result. However, there is one operation that you should avoid: calling the same measure twice, even if the value desired is the same.
For those of you that have some programming background, consider that referencing a measure is like calling a function when this happens in a row context. Being in the second argument of SUMX, we are exactly in that condition.

Thus, a better way to express our intention is:

Positive Balances :=
SUMX (
    Customer,
    VAR CustomerBalance = [Balance]
    RETURN
        IF (
            CustomerBalance > 0, 
            CustomerBalance
        )
)

The result is identical, but the code could run faster. And even if it does not run faster in this specific case… believe me, in more complex expression the difference might be very visible.

From a semantic point of view, we are forcing the engine to evaluate the Balance measure only once. This is the reason we can get better performance. More important, this also saves us from possible undesired side effects of different filter contexts that could evaluate the same measure. If your expression is more complex than the two trivial examples above, this could happen more easily than you can imagine. And when this happens, you will spend precious time trying to understand why the numbers are wrong.

Improve performance and readability, makes your code safer: use variables in DAX!