Variables in DAX: more readable and faster measures
Introduced in DAX in 2015, variables (VAR/RETURN) are perhaps the most impactful addition to the language. They let you name sub-expressions, making code more readable and potentially faster.
Syntax
Measure =
VAR vSales = SUM(fSales[Revenue])
VAR vCost = SUM(fSales[Cost])
VAR vMargin = vSales - vCost
RETURN
DIVIDE(vMargin, vSales)
Readability benefits
Compare with the version without variables:
-- Without variables (hard to read and maintain)
Margin % = DIVIDE(
SUM(fSales[Revenue]) - SUM(fSales[Cost]),
SUM(fSales[Revenue])
)
With variables, each part has a semantic name. Other team members (or you in 6 months) immediately understand the intent.
Performance benefits
A variable is evaluated only once in the filter context where it is declared. If the same sub-expression appears three times in the measure, without variables it is evaluated three times; with variables, it is evaluated once and the result reused.
Variables for debugging
Debug Measure =
VAR vBase = CALCULATE(SUM(fSales[Revenue]), REMOVEFILTERS())
VAR vFiltered = SUM(fSales[Revenue])
RETURN
"Base: " & vBase & " | Filtered: " & vFiltered
Change the RETURN to reveal intermediate values during development, without altering the final logic.
Important limitation
A variable captures the filter context at the moment it is declared. If the context changes afterwards (e.g. inside a CALCULATE), the variable is not re-evaluated. This behavior is intentional and consistent, but worth knowing.
Conclusion
Use VAR/RETURN in every measure with more than one sub-expression. The cost is zero and the gains in readability and maintenance are enormous.