DAX4_001
0 (0 Likes / 0 Dislikes)
You can use variables in your DAX expressions
to avoid repeating parts of your DAX expressions.
Let's hear Alberto talk a bit more about how you can use them and why they're really useful.
[Alberto] The last thing which is extremely useful and new in Power BI—
but this is also supported in Excel 2016—
is the usage of variables. Variables are extremely powerful
and they are extremely useful to use even if I can—
I understand that if you are new to DAX right now,
you look at them and say, "Well, why are they so useful?"
It will come later in the day. But basically you can define a variable—
wherever you have a DAX expression you define the variable saying
your TotalQuantity is the SUM of Sales[Quantity].
And then you refer to the variable inside your code.
So the pattern is always VAR and then RETURN,
where VAR defines the variable and RETURN returns the result of the expression.
Inside the return pattern, you can use the variable multiple times.
It is important first of all for readability of the code—
because this might be a very complex expression that you don't want to repeat multiple times
in your code. You write it only once, and once it's there you can use it as many times as you want.
And the second very important point is that variables guarantee you
that the evaluation happens only once. So if you use SUM of Sales[Quantity],
SUM is a very fast operation and you typically don't worry about performances.
But if that was a much more complex expression,
then repeating its description multiple times might lead to the evaluation
of the expression multiple times. And this, of course, is going to kill the performance of your measure.
Using variables guarantees that evaluation happens only once.
It happens here and here it's just used as a value which is stored in the cache of the model.