How to Use VAR and RETURN in DAX in Power BI
In DAX,
VAR lets you store a value or expression result in a variable, and RETURN outputs the final result using those variables. This helps make formulas easier to read and improves performance by avoiding repeated calculations.Syntax
The basic syntax of using VAR and RETURN in DAX is:
VAR: Defines a variable and assigns it a value or expression.RETURN: Specifies the expression that uses the variables and produces the final result.
You can define multiple VAR variables before the RETURN statement.
DAX
MeasureName =
VAR VariableName = Expression
RETURN
ResultExpressionUsingVariableNameExample
This example calculates the percentage of total sales for each product category using VAR to store intermediate values and RETURN to output the final percentage.
DAX
Category Sales % =
VAR TotalSales = SUM(Sales[Amount])
VAR OverallSales = CALCULATE(SUM(Sales[Amount]), ALL(Sales[Category]))
RETURN
DIVIDE(TotalSales, OverallSales, 0)Output
For a category with sales 5000 and overall sales 20000, output is 0.25 (25%)
Common Pitfalls
Common mistakes when using VAR and RETURN include:
- Not using
RETURNafterVARdeclarations, which causes syntax errors. - Trying to use variables outside the
RETURNstatement. - Defining variables with complex expressions but not reusing them, missing performance benefits.
Always remember RETURN is required to output the final result.
DAX
WrongMeasure =
VAR Total = SUM(Sales[Amount])
// Missing RETURN causes error
CorrectMeasure =
VAR Total = SUM(Sales[Amount])
RETURN
TotalQuick Reference
| Keyword | Purpose | Notes |
|---|---|---|
| VAR | Defines a variable to store a value or expression | Can define multiple variables before RETURN |
| RETURN | Outputs the final result using variables | Must be used after VAR declarations |
| Variables | Hold intermediate results | Improve readability and performance |
| Scope | Variables exist only within the measure or calculated column | Cannot be accessed outside |
Key Takeaways
Use VAR to store intermediate calculations and RETURN to output the final result in DAX.
Always include RETURN after VAR declarations to avoid syntax errors.
Variables improve formula readability and can boost performance by avoiding repeated calculations.
You can define multiple VAR variables before RETURN in a single measure.
Variables are local to the measure and cannot be used outside their scope.