# POWER BI TUTORIAL : Using Variables in DAX

Earlier this year, new version of DAX was released. One of the key features with this release is the support for variables. Variables makes writing DAX code easier. Variables also make code easier to read and understand.

Download sample data here. Data represents sales for a particular store. Products are categorized by seasonality and color. We want to calculate the % of in season product that are sold in the store. We can do this without using variables:

% In Season Sales = DIVIDE (CALCULATE(

SUM(‘Sales'[UnitsSold]),’Sales'[IsSeason]=1

)

, SUM(‘Sales'[UnitsSold])

)

Now let’s do the same using variables.

% In Season Sales (With Var) =

VAR InSeasonSales=

CALCULATE(

SUM(‘Sales'[UnitsSold]),’Sales'[IsSeason]=1

)

VAR AllSales=

SUM(‘Sales'[UnitsSold])

RETURN

DIVIDE(InSeasonSales, AllSales)

Notice we created two variables:

VAR InSeasonSales is used to calculate the sales of seasonal products.

VAR AllSales is used to calculate sales of the all the products.

And DIVIDE function is used to get the percentage.

Notice that creating variables made the code easy to read.

Let’s look at something a little more complex. We need to calculate percentage of Red in season products that are sold.

% In Season Red Sales =

VAR InSeasonRed=

CALCULATE(

SUM(‘Sales'[UnitsSold]),’Sales'[IsSeason]=1, ‘Sales'[ProductColor]=”Red”

)

VAR InSeasonSales =

CALCULATE(

SUM(‘Sales'[UnitsSold]),’Sales'[IsSeason]=1

)

RETURN

DIVIDE(InSeasonRed, InSeasonSales)

Notice in this case, variables InSeasonRed and InSeasonSales has different filters. Writing them as variables makes this apparent and easy to read. As the measures get complex, using variables is a huge advantage to both write and read code.

Here are a few good references:

https://www.sqlbi.com/articles/variables-in-dax/

http://www.powerpivotblog.nl/dax-now-has-variable-support/

http://sqlblog.com/blogs/marco_russo/archive/2015/04/22/dax-measures-in-power-bi-designer-and-new-dax-syntax-finally-here.aspx