Ravindra BagaleCourses & study guides

13. DAX: Data Analysis Expressions

13.18 Variables: VAR and RETURN

Variables store an intermediate result, making formulas easier to read, easier to debug and often faster (a variable is calculated once, even if used several times).

Store Health =
VAR OrdersCount = [Total Orders]
VAR AvgTime = [Avg Delivery Time (mins)]
VAR CancelRate = [Cancellation Rate]
RETURN
    SWITCH(TRUE(),
        ISBLANK(OrdersCount), BLANK(),
        AvgTime <= 10 && CancelRate < 0.02, "Excellent",
        AvgTime <= 15 && CancelRate < 0.05, "Good",
        "Needs Attention")

(The thresholds are example values for practice, not industry benchmarks.)

Aata he bagha: rules: define variables with VAR name = expression; finish with one RETURN. A variable is evaluated where it is defined, in the context at that point – it does not change later, even inside CALCULATE.

Debugging with variables

To check an intermediate value, temporarily change RETURN … to RETURN AvgTime. You can also test measures in DAX query view using EVALUATE and SUMMARIZECOLUMNS.

EVALUATE
SUMMARIZECOLUMNS(
    DarkStore[City],
    Orders[Platform],
    "Orders", [Total Orders],
    "Avg Mins", [Avg Delivery Time (mins)],
    "Cancel %", [Cancellation Rate]
)
ORDER BY [Orders] DESC

Variables vapraychi savay lavun ghya. Formula vachayla sopa hoto aani chuk shodhayla pan.

Ravindra Bagale's Tip

A common mistake is defining a variable and expecting it to change inside a later CALCULATE. Variables are evaluated once, where they are defined. Use this on purpose to "freeze" a value, and return a variable on its own when you need to debug a long measure. Keep this in mind!